Bez popisu

momoize.js 655B

12345678910111213141516171819202122
  1. 'use strict';
  2. function defaultIsNewArgEqualToLast(newArgs, lastArgs) {
  3. return newArgs.length === lastArgs.length && newArgs.every((arg, index) => arg === lastArgs[index]);
  4. }
  5. export default function memoize(resultCallback, isNewArgEqualToLast) {
  6. let lastArgs = [];
  7. let lastResult;
  8. let calledOnce = false;
  9. const isEqual = isNewArgEqualToLast || defaultIsNewArgEqualToLast;
  10. const result = function(...newArgs) {
  11. if (calledOnce && isEqual(newArgs, lastArgs)) {
  12. return lastResult;
  13. }
  14. calledOnce = true;
  15. lastArgs = newArgs;
  16. lastResult = resultCallback.apply(this, newArgs);
  17. return lastResult;
  18. };
  19. return result;
  20. }