So I am using an inner function for closure and to be able to pass in an unknown amount of arguments. The function is supposed to use memoization of some kind (I chose to use an object) to check and see if the result of running arguments through a callback have already been computed and stored. Here is the function I have written so far...
function memoize(func) {
// Define an object to hold results
let obj = {}
// define an inner function for closure that takes an argument
function inner(...arg) {
if (obj[arg]) {
return obj[arg]
} else {
obj[arg] = func(...arg);
return obj[arg];
}
}
return inner;
}
I am getting an error that my function "should work with objects as arguments"... Currently, I am unsure why my current code WON'T work with objects as arguments... So if someone could explain that, it would be greatly appreciated. Here is the algorithm used to test my function...
it('should work with objects as arguments', () => {
const firstTime = timeCheck({ foo: 'bar' });
wait(5);
const secondTime = fastTimeCheck({ foo: 'bar' });
wait(5);
expect(firstTime).to.not.equal(secondTime);
expect(fastTimeCheck({ foo: 'bar' })).to.equal(secondTime);
expect(fastTimeCheck({ foo: 'bar' })).to.not.equal(fastTimeCheck({ different: 'result' }));
});
If you have the time. I would appreciate knowing why my current function is not working with objects as arguments... Also, how can I modify what I have written to satisfy the test algorithm.
Property names are string or Symbol. Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'. See Property accessors
So when you call obj[arg], you actually call something like obj[arg.toString()]. Here arg is the array of the arguments, like [{foo: 'bar'}]. Try calling [{foo: 'bar'}].toString() and you'll get [object Object]. See Array.prototype.toString() and Object.prototype.toString().
That means for every object argument, you will get the same key.