You need to remember the arguments that you're passing into your function such that when you call your function again with the same arguments it returns a string, otherwise, if you call it with an argument that you haven't used before it returns a number.
This can be achieved by building an object, which your inner function closes over. The object will store keys which are based on the arguments passed into the function. The value of each key will be the result of calling the function with the arguments stored at the key.
When you call your function with arguments, you can check to see if the object you made has the arguments you passed in. If so, you can return the value stored at the arguments key of your object. Otherwise, if the arguments aren't a key in your object, you can set the key and the value, and return the value of the object you just set.
See code comments for further details:
function stored(callback) {
const memo = {}; // used to store already seen arguments and their respective return values
return function(n) {
if (typeof n === 'string') {
return 'Please enter a valid number'
} else if(n in memo) { // if `n` has already been seen, grab the "remembered" result.
return `${n}: ${memo[n]}`;
} else { // if function hasn't been called with `n` before, then save the result
memo[n] = callback(n);
return memo[n];
}
}
}
const cube = (n) => n ** 3;
const cubeStored = stored(cube);
console.log(cubeStored(2)) //--> 8
console.log(cubeStored(2)) //--> '2: 8'
console.log(cubeStored(3)) //--> 27
console.log(cubeStored(3)) //--> '3: 27'
console.log(cubeStored('a')) //--> "Please enter a valid number"
console.log(cubeStored('a')) //--> "Please enter a valid number"
console.log(cubeStored(2)) //--> '2: 8'
The above can be generalized a little more to handle n arguments by using the rest parameter syntax (...):
function stored(callback) {
const memo = {};
return function(...args) {
const key = JSON.stringify(args);
if (args.length <= 0 || typeof args[0] === 'string') {
return 'Please enter a valid number'
} else if(key in memo) {
return `${key}: ${memo[key]}`;
} else { // if function hasn't been called with `n` before, then save the result
memo[key] = callback(...args);
return memo[key];
}
}
}
const cube = (n) => n ** 3;
const cubeStored = stored(cube);
console.log(cubeStored(2)) //--> 8
console.log(cubeStored(2)) //--> '2: 8'
console.log(cubeStored(3)) //--> 27
console.log(cubeStored(3)) //--> '3: 27'
console.log(cubeStored('a')) //--> "Please enter a valid number"
console.log(cubeStored('a')) //--> "Please enter a valid number"
console.log(cubeStored(2)) //--> '2: 8'
returnstatements one after the other? The second will never be executed.typeof n !== 'number', nottypeof n === 'string'for that check