Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Created March 28, 2019 15:23
Show Gist options
  • Save Akiyamka/b9bdcb6ba69fa4116c789ba099b3544e to your computer and use it in GitHub Desktop.
Save Akiyamka/b9bdcb6ba69fa4116c789ba099b3544e to your computer and use it in GitHub Desktop.
export default class Watcher {
constructor() {
this._mem = [];
}
_compareFunction(val1, val2) {
return Object.is(val1, val2);
}
setCallbacks(callbacks) {
callbacks.forEach((cb, i) => {
this._mem[i] = cb(this._mem[i]);
});
}
whenChange(variables, callback, customCompare) {
return prevVariables => {
if (prevVariables === undefined) {
callback(...variables);
return variables;
}
const nothingChanges = variables.every(
(currVar, i) => typeof customCompare === 'function'
? customCompare(currVar, prevVariables[i])
: this._compareFunction(currVar, prevVariables[i])
);
if (nothingChanges) return variables;
callback(...variables);
return variables;
};
}
}
@Akiyamka
Copy link
Author

Akiyamka commented Mar 28, 2019

test('whenChange() with [props] shoot callback only when props change', t => {
  let counter = 0;

  let props = 'foo';
  watcher.setCallbacks([
    watcher.whenChange([props], () => counter = counter + 1)
  ]);

  watcher.setCallbacks([
    watcher.whenChange([props], () => counter = counter + 1) // Must not call
  ]);

  props = 'bar';
  watcher.setCallbacks([
    watcher.whenChange([props], () => counter = counter + 1)
  ]);
  
  t.is(counter, 2);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment