Lodash memoize key 当被记忆的功能接受功能时?
Lodash memoize key when the function being memoized accepts functions?
我有一个大型数据集,我经常通过首先对其应用过滤器来查询。我想缓存和重用我使用的不同过滤器函数的结果,因为这部分可能很昂贵。这是对此的粗略模拟:
const a = x => x + 1;
const b = x => x + 2;
const m = _.memoize(
f => (console.log('filtering data'), f(314159)),
f => String(f)
);
console.log(m(a));
console.log(m(b));
console.log(m(a));
console.log(m(b));
这里 "a" 和 "b" 是我想使用的过滤器函数,"m" 每次都作用于相同的数据。
如何指定 _.memoize 函数的键?
上面的方法有效,但我使用的是感觉不对的函数的字符串表示形式。有没有更好的方法?
我担心应用缩小时这不安全。在我的实际代码中,"memoize" 部分在一个 ES6 模块中,"a" 和 "b" 部分在另一个模块中,对 "m" 的调用在几个不同的模块中导入 "a" 和 "b" 函数。像这样跨模块的字符串表示是否稳定?转换为字符串表示的速度快吗?
我能想到的唯一选择是创建一个字符串 -> 函数字典,这样你就可以像 m("a") 这样调用,但是 JavaScript 如果名称错了。
The above works but I'm using the string representation of the function which feels wrong.
确实如此。
I'm worried this isn't safe when minification is applied.
不,缩小不是问题。不同的功能被缩小到不同的代码。
问题是闭包:
const addTo = x => y => x + y
const a = addTo(1),
b = addTo(2);
console.log(String(a) === String(b));
您只能通过对象标识可靠地比较函数。最好的方法可能是更新 Lodash 以使用不需要任何字符串化的 ES6 WeakMap
。
只要没有,都可以用
const id = Symbol("function identity");
let count = 0;
function toMemoizeKey(fn) {
return fn[id] || (fn[id] = ++count);
}
我有一个大型数据集,我经常通过首先对其应用过滤器来查询。我想缓存和重用我使用的不同过滤器函数的结果,因为这部分可能很昂贵。这是对此的粗略模拟:
const a = x => x + 1;
const b = x => x + 2;
const m = _.memoize(
f => (console.log('filtering data'), f(314159)),
f => String(f)
);
console.log(m(a));
console.log(m(b));
console.log(m(a));
console.log(m(b));
这里 "a" 和 "b" 是我想使用的过滤器函数,"m" 每次都作用于相同的数据。
如何指定 _.memoize 函数的键?
上面的方法有效,但我使用的是感觉不对的函数的字符串表示形式。有没有更好的方法?
我担心应用缩小时这不安全。在我的实际代码中,"memoize" 部分在一个 ES6 模块中,"a" 和 "b" 部分在另一个模块中,对 "m" 的调用在几个不同的模块中导入 "a" 和 "b" 函数。像这样跨模块的字符串表示是否稳定?转换为字符串表示的速度快吗?
我能想到的唯一选择是创建一个字符串 -> 函数字典,这样你就可以像 m("a") 这样调用,但是 JavaScript 如果名称错了。
The above works but I'm using the string representation of the function which feels wrong.
确实如此。
I'm worried this isn't safe when minification is applied.
不,缩小不是问题。不同的功能被缩小到不同的代码。
问题是闭包:
const addTo = x => y => x + y
const a = addTo(1),
b = addTo(2);
console.log(String(a) === String(b));
您只能通过对象标识可靠地比较函数。最好的方法可能是更新 Lodash 以使用不需要任何字符串化的 ES6 WeakMap
。
只要没有,都可以用
const id = Symbol("function identity");
let count = 0;
function toMemoizeKey(fn) {
return fn[id] || (fn[id] = ++count);
}