All quizzesMedium
Higher-Order Functions — Series 3
Preview — 3 of 10 questions
What is logged?
javascript
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = args.join(',');
if (cache.has(key)) return cache.get(key);
const value = fn(...args);
cache.set(key, value);
return value;
};
}
let calls = 0;
const countParts = memoize((...parts) => {
calls++;
return parts.length;
});
console.log(countParts('a,b'), countParts('a', 'b'), calls);A1 2 2
B1 1 1
C2 2 1
D1 2 1
What is logged?
javascript
function once(fn) {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
let n = 0;
const init = once((x) => {
n++;
return x * 2;
});
console.log(init(5), init(10), n);A10 20 2
B10 undefined 1
C10 10 2
D10 10 1
What is logged?
javascript
const compose = (...fns) => (x) => fns.reduceRight((acc, f) => f(acc), x);
const inc = (n) => n + 1;
const double = (n) => n * 2;
console.log(compose(inc, double)(5), compose(double, inc)(5));A11 12
B12 11
C11 11
D12 12
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.