将参数引入另一个函数
问题描述:
一个参数 - 另一个函数 - 并返回该函数的“memoized”版本。一个“memoized”版本的函数缓存并返回其调用结果,以便当它再次用相同的输入调用时,它不会运行它的计算,而是从缓存中返回结果。请注意,以前的结果应该可以以任何顺序检索,而无需重新计算。将参数引入另一个函数
foo = function (x) {
console.log("calculating!");
return x + 5;
}
var memoizedFoo = memoize(foo);
memoizedFoo(5);
// calculating!
// 10
memoizedFoo(5);
// 10 (notice how 'calculating!' is not printed this time)
memoizedFoo(10);
// calculating!
// 15
答
我假设问题是如何编写memoize
。您可以将给定参数的第一个结果存储在容器中,并返回将使用该容器的函数(如果可用)。
下面是一个ES5例子,它仅适用于自变量值,可以有效地转换为字符串,如字符串,数字,布尔值:
function memoize(f) {
// Storage for this function's results
var values = Object.create(null);
return function(arg) {
// Already have it?
if (Object.hasOwnProperty.call(values, arg)) {
// Yes, return it
return values[arg];
}
// No, get it, remember it, and return it
return values[arg] = f(arg);
};
}
var foo = function (x) {
console.log("calculating!");
return x + 5;
};
var memoizedFoo = memoize(foo);
console.log(memoizedFoo(5));
// calculating!
// 10
console.log(memoizedFoo(5));
// 10
console.log(memoizedFoo(10));
// calculating!
// 15
如果您需要支持其他种类您需要使用其他结构或填充。这给我们带来...
...在ES2015 +,我们可以使用Map
,这使得它具有更广泛的参数值的工作:
function memoize(f) {
// Storage for this function's results
const values = new Map();
return function(arg) {
// Already have it?
if (values.has(arg)) {
// Yes, return it
return values.get(arg);
}
// No, get it, remember it, and return it
const value = f(arg);
values.set(arg, value);
return value;
};
}
const foo = function (x) {
console.log("calculating!");
return x.foo + 5;
};
const memoizedFoo = memoize(foo);
const firstArg = {foo:5};
console.log(memoizedFoo(firstArg));
// calculating!
// 10
console.log(memoizedFoo(firstArg));
// 10
const secondArg = {foo:10};
console.log(memoizedFoo(secondArg));
// calculating!
// 15
// Note that maps consider equivalent but distinct objects as different (of course),
// so we don't get the memoized reslt from
// `firstArg` here
const thirdArg = {foo:5};
console.log(memoizedFoo(secondArg));
// calculating!
// 10
什么*是*简单的问题? –
@ T.J.Crowder,那为什么错了,我有这个问题要解决,但是没搞懂怎么弄就是工作, – faisal
问题是你没问过问。 –