Using Observables in real life
Nicolas Carlo
464

I’d say main improvement achieved here should rather be attributed to usage of debounce pattern, and not necessarily Rx.Observable (that is quite subjective).

Code gets way cleaner just by basing logic on debounce :

const ENTER_KEY_CODE = 13;
const MAX_INTERVAL_BETWEEN_EVENTS_IN_MS = 50;
const keyCodes = [];
const processScan = debounce(() => {
if (isFromScan()) fillInputWith();
keyCodes.length = 0;
}, MAX_INTERVAL_BETWEEN_EVENTS_IN_MS);
function isFromScan () {
return keyCodes.length > 1 && keyCodes[keyCodes.length - 1] === ENTER_KEY_CODE;
}
function fillInputWith () {
// …
}
document.addEventListener("keypress", (ev) => {
keyCodes.push(ev.keyCode);
processScan();
});