tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

memoize.js (1403B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
      4 
      5 function hasValue(keys, store) {
      6  let currentStore = store;
      7  for (const key of keys) {
      8    if (!currentStore || !currentStore.has(key)) {
      9      return false;
     10    }
     11 
     12    currentStore = currentStore.get(key);
     13  }
     14  return true;
     15 }
     16 
     17 function getValue(keys, store) {
     18  let currentStore = store;
     19  for (const key of keys) {
     20    if (!currentStore) {
     21      return null;
     22    }
     23    currentStore = currentStore.get(key);
     24  }
     25 
     26  return currentStore;
     27 }
     28 
     29 function setValue(keys, store, value) {
     30  const keysExceptLast = keys.slice(0, -1);
     31  const lastKey = keys[keys.length - 1];
     32 
     33  let currentStore = store;
     34  for (const key of keysExceptLast) {
     35    if (!currentStore) {
     36      return;
     37    }
     38 
     39    if (!currentStore.has(key)) {
     40      currentStore.set(key, new WeakMap());
     41    }
     42    currentStore = currentStore.get(key);
     43  }
     44 
     45  if (currentStore) {
     46    currentStore.set(lastKey, value);
     47  }
     48 }
     49 
     50 // memoize with n arguments
     51 export default function memoize(func) {
     52  const store = new WeakMap();
     53 
     54  return function (...keys) {
     55    if (hasValue(keys, store)) {
     56      return getValue(keys, store);
     57    }
     58 
     59    const newValue = func.apply(null, keys);
     60    setValue(keys, store, newValue);
     61    return newValue;
     62  };
     63 }