How do I define foo
to make the following code work correctly as expected (in JavaScript)?
foo[1] + 1 // 2
foo[1][2] + 1 // 4
foo[10][20][30] + 1 // 61
foo[100][200][300] + 1 // 601
This is an interview question I once met.
This sounds like a new take on the old variadic chainable sum
function puzzle, with proxy member access instead of function calls. The possible approaches are still the same though, and the …+1
gives away that they are looking for the valueOf
solution. In the same vein, foo+1
would be 1
and +foo
/Number(foo)
would be 0
.
const handler = {
get(target, propName, receiver) {
if (typeof propName == 'string' && /^\d+$/.test(propName))
return sumProxy(target + parseInt(propName, 10));
else
return Reflect.get(target, propName, receiver);
}
};
function sumProxy(value) {
return new Proxy({
valueOf() { return value; }
}, handler);
}
const foo = sumProxy(0);
console.log(foo + 1); // 1
console.log(foo[1] + 1); // 2
console.log(foo[1][2] + 1); // 4
console.log(foo[10][20][30] + 1); // 61
console.log(foo[100][200][300] + 1); // 601