UNPKG

react-lazy-cache

Version:

A utility to lazily calculate and cache values in a react component based on props

61 lines (54 loc) 1.67 kB
'use strict'; exports.__esModule = true; exports['default'] = lazyCache; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _deepEqual = require('deep-equal'); var _deepEqual2 = _interopRequireDefault(_deepEqual); function lazyCache(component, calculators) { var allProps = []; var cache = {}; var api = {}; var uncache = function uncache(changedProp) { Object.keys(cache).forEach(function (key) { if (~cache[key].props.indexOf(changedProp)) { delete cache[key].value; uncache(key); } }); }; Object.keys(calculators).forEach(function (key) { var fn = calculators[key].fn; var props = calculators[key].params; props.forEach(function (param) { if (! ~allProps.indexOf(param)) { allProps.push(param); } }); cache[key] = { props: props }; Object.defineProperty(api, key, { get: function get() { var cached = cache[key]; if (cached && cached.value !== undefined) { return cached.value; } var params = props.map(function (prop) { return component.props[prop] || api[prop]; }); var value = fn.apply(undefined, params); cache[key] = { props: props, value: value }; return value; } }); }); api.componentWillReceiveProps = function (nextProps) { var diffProps = []; allProps.forEach(function (prop) { if (!_deepEqual2['default'](component.props[prop], nextProps[prop])) { diffProps.push(prop); } }); diffProps.forEach(uncache); }; return api; } module.exports = exports['default'];