All files memoize.js

94.44% Statements 34/36
88.89% Branches 16/18
100% Functions 7/7
93.55% Lines 29/31
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 631x 1x 1x     7x         7x       7x       19x         19x 33x 12x       7x       7x 7x 43x 7x   7x 2x   7x   7x   4x   7x 3x     7x   66x 22x 22x 15x 15x   22x      
import deepEquals from './deepEquals'
import lruCache from './lruCache'
import singletonCache from './singletonCache'
 
function createCache(limit, equals) {
  return limit === 1 ? singletonCache(equals) : lruCache(limit, equals)
}
 
function createEqualsFn(basicEquals, deepObjects) {
  // 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) {
  let limit = 1
  let equals = (valueA, valueB) => valueA === valueB
  let deepObjects = false
 
  if (typeof config[0] === 'number') {
    limit = config.shift()
  }
  Iif (typeof config[0] === 'function') {
    equals = config.shift()
  } 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) => {
    let value = cache.get(args)
    if (value === undefined) {
      value = fn.apply(fn, args)
      cache.put(args, value)
    }
    return value
  }
}