简体   繁体   English

Lodash记忆键何时被记忆的功能接受功能?

[英]Lodash memoize key when the function being memoized accepts functions?

I have a large data collection that I frequently query by first applying a filter to it. 我有一个大的数据集合,我经常通过首先对其应用过滤器来查询。 I want to cache and reuse the results of the different filter functions I use because this part can be expensive. 我想缓存和重用我使用的不同过滤器函数的结果,因为这部分可能会很昂贵。 Here's a rough simulation of this: 这是一个粗略的模拟:

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));

Here "a" and "b" would be the filter functions I want to use and "m" is acting on the same data each time. 在这里,“ a”和“ b”将是我要使用的过滤器函数,并且“ m”每次都作用于相同的数据。

How do I specify the key for the _.memoize function? 如何为_.memoize函数指定键?

The above works but I'm using the string representation of the function which feels wrong. 上面的作品,但我正在使用该函数的字符串表示形式,这感觉不对。 Is there a better way? 有没有更好的办法?

I'm worried this isn't safe when minification is applied. 我担心应用缩小时这是不安全的。 In my actual code, the "memoize" part is in one ES6 module, the "a" and "b" parts are in another module and the calls to "m" are in several different modules which import the "a" and "b" function. 在我的实际代码中,“ memoize”部分在一个ES6模块中,“ a”和“ b”部分在另一个模块中,对“ m”的调用在几个导入了“ a”和“ b”的不同模块中”功能。 Will the string representation be stable across modules like this? 字符串表示形式在这样的模块之间稳定吗? Is converting to the string representation fast? 转换为字符串表示是否很快?

The only alternative I can think of is to create a string -> function dictionary so you would do calls like m("a") but JavaScript linters won't pick up if the name is wrong. 我唯一想到的替代方法是创建一个字符串->函数字典,这样您就可以进行m(“ a”)之类的调用,但是如果名称错误,则JavaScript linter不会接听。

The above works but I'm using the string representation of the function which feels wrong. 上面的作品,但我正在使用该函数的字符串表示形式,这感觉不对。

Indeed. 确实。

I'm worried this isn't safe when minification is applied. 我担心应用缩小时这是不安全的。

No, minification is not the problem. 不,缩小不是问题。 Different functions get minified to different code. 不同的函数被缩小为不同的代码。

The problem is closures: 问题是闭包:

const addTo = x => y => x + y
const a = addTo(1),
      b = addTo(2);
console.log(String(a) === String(b));

You can only reliably compare functions by their object identity. 您只能通过功能的对象标识可靠地比较功能。 The best way would probably be to update Lodash to use an ES6 WeakMap that doesn't require any stringification. 最好的方法可能是更新Lodash以使用不需要任何字符串化的ES6 WeakMap

As long as such is not available, you can use 只要不可用,就可以使用

const id = Symbol("function identity");
let count = 0;
function toMemoizeKey(fn) {
    return fn[id] || (fn[id] = ++count);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM