/
githubmirror
/
gutenberg
Обзор
Документация
Войти
/
githubmirror
/
gutenberg
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
trunk
packages/core-data/src/utils/with-weak-map-cache.js
32 строки
856 B
Marin Atanasov
Lodash: Refactor away from _.isObjectLike() (#41701)
14 июн 2022, 15:35
Не верифицирован
14 июн 2022, 15:35
c26168f
Код
Авторство
О чём код?
/** * Given a function, returns an enhanced function which caches the result and * tracks in WeakMap. The result is only cached if the original function is * passed a valid object-like argument (requirement for WeakMap key). * * @param {Function} fn Original function. * * @return {Function} Enhanced caching function. */ function withWeakMapCache( fn ) { const cache = new WeakMap(); return ( key ) => { let value; if ( cache.has( key ) ) { value = cache.get( key ); } else { value = fn( key ); // Can reach here if key is not valid for WeakMap, since `has` // will return false for invalid key. Since `set` will throw, // ensure that key is valid before setting into cache. if ( key !== null && typeof key === 'object' ) { cache.set( key, value ); } } return value; }; } export default withWeakMapCache;