Skip to content

Commit

Permalink
bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruben-Arushanyan committed Oct 3, 2023
1 parent 2b40aa6 commit dd6ab90
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Store.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SingularEventEmitter } from 'secure-event-emitter'
import { isFunction, eq } from './utils'
import { isFunction, eq, memoizeByArgs } from './utils'


class Store {
Expand All @@ -26,7 +26,11 @@ class Store {
}

subscribe = (cb) => {
const _cb = () => cb(this.state, this.prevState)
cb = memoizeByArgs(cb)
const _cb = () => {
cb(this.state, this.prevState)
}

this.#emitter.on(_cb)
return () => this.#emitter.off(_cb)
}
Expand Down
33 changes: 33 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,36 @@
export const isFunction = (x) => typeof x === 'function'
export const eq = (x, y) => (x === y) || (x !== x && y !== y)
export const memoizeByArgs = (fn) => {
let lastArgs;
let lastResult;

const memoFn = (...args) => {
if (!lastArgs || !isSameArgs(lastArgs, args)) {
lastResult = fn(...args);
}
lastArgs = args;
return lastResult;
};
memoFn.clearCache = () => {
lastArgs = undefined;
lastResult = undefined;
};
return memoFn;
};






const isSameArgs = (args1, args2) => {
if (args1.length !== args2.length) {
return false;
}
for (let i = 0; i < args1.length; ++i) {
if (!eq(args1[i], args2[i])) {
return false;
}
}
return true;
};

0 comments on commit dd6ab90

Please sign in to comment.