morse-code / lib /rules.js
RemiFabre
feat: Demo mode for filming two robots conversing
a33a583
Raw
History Blame Contribute Delete
1.03 kB
/**
* Demo-mode auto-reply rules: "if you hear X, answer Y".
*
* Matching is normalized — uppercased, with spaces and punctuation stripped —
* so a rule typed as "U OK?" still fires on a decoded "U OK" or "UOK". Antenna
* Morse won't reliably carry punctuation, so we never require an exact match.
*
* Pure module (no DOM/audio) so the matching logic is unit-tested directly.
*/
export function normalizePhrase(s) {
return String(s).toUpperCase().replace(/[^A-Z0-9]/g, "");
}
/** Default conversation for the two-robot demo (short = fewer antenna taps). */
export const DEFAULT_RULES = [
{ input: "U OK", output: "Y" },
{ input: "SOS", output: "WTF" },
];
/**
* Find the first rule whose (normalized) input equals the (normalized)
* decoded text. Returns the rule or null.
*/
export function matchRule(text, rules) {
const n = normalizePhrase(text);
if (!n) return null;
return (rules || []).find(
(r) => r && r.input && r.output && normalizePhrase(r.input) === n,
) || null;
}