Skip to content

Instantly share code, notes, and snippets.

@jniac
Created April 15, 2021 16:49
Show Gist options
  • Save jniac/a8a1e4e7c0a3030311db9c5d7818defc to your computer and use it in GitHub Desktop.
Save jniac/a8a1e4e7c0a3030311db9c5d7818defc to your computer and use it in GitHub Desktop.
Little value wrapper, animation purpose (tracking value changes)
/**
* TO BE DISCUSSED.
* This is a little wrapper that allows to animate any "abstract" variable.
* Callback may be provided to react on any value change.
* "old" allows to know the "old" (previous) value.
*/
type Callback = (variable: Variable) => void
export default class Variable {
#value = 0;
#old = 0;
get old() { return this.#old; }
get value() { return this.#value; }
set value(value: number) {
this.setValue(value);
}
#callback = new Set<Callback>();
constructor(initialValue: number, callback?: Callback) {
this.#value = initialValue;
this.#old = initialValue;
if (callback !== undefined) {
this.#callback.add(callback);
}
}
addCallback(callback: Callback) {
this.#callback.add(callback);
const unsubscribe = () => this.#callback.delete(callback);
return unsubscribe;
}
setValue(value: number) {
if (value === this.#value) {
return;
}
this.#old = this.#value;
this.#value = value;
this.#callback.forEach((cb) => cb(this));
}
goneThrough(threshold: number) {
return (
(this.#value >= threshold && this.#old < threshold)
|| (this.#value < threshold && this.#old >= threshold)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment