在Javascript中从下栏写入.备忘录
我目前正在学习Javascript,正在做underbar项目(重新编写_underbar库) 我已经解决了所有问题,只有一个,因为我一直在回忆 这是我当前的代码在Javascript中从下栏写入.备忘录,javascript,Javascript,我目前正在学习Javascript,正在做underbar项目(重新编写_underbar库) 我已经解决了所有问题,只有一个,因为我一直在回忆 这是我当前的代码 _.memoize = function(func) { var cache = {}; var slice = Array.prototype.slice; return function() { var args = slice.call(arguments); if (args
_.memoize = function(func) {
var cache = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in cache) {
return cache[args];
} else {
return (cache[args] = func.apply(this, args));
}
}
};
这是我未能通过的测试用例
// Here, we wrap a dummy function in a spy. A spy is a wrapper function (much like _.memoize
// or _.once) that keeps track of interesting information about the function it's spying on;
// e.g. whether or not the function has been called.
it('should run the memoized function twice when given an array and then given a list of arguments', function() {
// Be careful how you are checking if a set of arguments has been passed in already
var spy = sinon.spy(function() { return 'Dummy output'; });
var memoSpy = _.memoize(spy);
memoSpy([1, 2, 3]);
expect(spy).to.have.been.calledOnce;
memoSpy(1, 2, 3);
expect(spy).to.have.been.calledTwice;
});
或者说“当给定一个数组,然后给定一个参数列表时,它应该运行两次记忆函数”
我试图通过检查第一个参数是否是数组来更改参数,如果不是,则将所有参数都设置为数组,但没有成功。我还尝试重新编写代码来保存结果,并使用斐波那契存储缓存,但它会运行函数两次
我将如何解决此测试用例
感谢使用
缓存[args]
没有多大意义,因为args
是一个数组,使用括号表示法将其转换为字符串。您可以将参数数组设置为其返回值,然后比较这些数组:
const{};
_.memoize=函数(func){
常量allArgs=[];
返回函数(…args){
//尝试在allArgs中查找匹配的参数
const result=allArgs.find(
item=>item.args.length==args.length&&item.args.every(
(arg,i)=>args[i]==arg
)
);
//如果找到匹配的参数数组,则返回结果:
if(result)返回result.returnValue;
const returnValue=func.apply(此参数为args);
allArgs.push({args,returnValue});
返回值;
}
};
常量memoizedSum=u.memoize((…args)=>{
log('called with',args);
返回参数reduce((a,b)=>a+b,0);
});
日志(memorizedsum(1,2,3));
日志(memorizedsum(1,2,3));
日志(memorizedsum(4,5,6))代码>提示:memoSpy(“1,2,3”)代码>。缓存中的args
具体做什么?其他提示:arguments
已经是一个数组。我想这个练习的目标是一个简单的JSON。stringifiy
如果保证所有的参数都是可序列化的,当然,但OP并没有这样说,而且这似乎不是一个安全的假设——它不会忠实地实现。下划线的版本不接受并正确缓存不可序列化的参数