All files memoize.js

93.33% Statements 28/30
88.89% Branches 16/18
100% Functions 7/7
92.59% Lines 25/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65              7x         7x       7x       19x         19x 33x 12x       7x         7x 43x 7x   7x 2x   7x   7x   4x   7x 3x     7x   7x 22x 22x 15x 15x   22x      
// @flow
import type { Config, Equals } from ".";
import deepEquals from "./deepEquals";
import lruCache from "./lruCache";
import singletonCache from "./singletonCache";
 
function createCache(limit: number, equals: Equals) {
  return limit === 1 ? singletonCache(equals) : lruCache(limit, equals);
}
 
function createEqualsFn(basicEquals: Equals, deepObjects: boolean) {
  // Choose strategy for basic or deep object equals
  const equals = deepObjects
    ? deepEquals(basicEquals, deepObjects)
    : basicEquals;
 
  return (valueA, valueB) => {
    // The arguments are always the argument array-like objects
 
    // Different lengths means they are not the same
    Iif (valueA.length !== valueB.length) {
      return false;
    }
 
    // Compare the values
    for (let index = 0; index < valueA.length; index += 1) {
      if (!equals(valueA[index], valueB[index])) {
        return false;
      }
    }
    // Found no conflicts
    return true;
  };
}
 
export default function memoize(...config: Config): Function => Function {
  let limit: number = 1;
  let equals: Equals = (valueA, valueB) => valueA === valueB;
  let deepObjects: boolean = false;
 
  if (typeof config[0] === "number") {
    limit = ((config.shift(): any): number);
  }
  Iif (typeof config[0] === "function") {
    equals = ((config.shift(): any): Function);
  } else if (typeof config[0] === "undefined") {
    // Support passing undefined equal argument;
    config.shift();
  }
  if (typeof config[0] === "boolean") {
    deepObjects = config[0];
  }
 
  const cache = createCache(limit, createEqualsFn(equals, deepObjects));
 
  return fn => (...args: any[]) => {
    let value = cache.get(args);
    if (value === undefined) {
      value = fn.apply(fn, args);
      cache.put(args, value);
    }
    return value;
  };
}