Higher-Order Functions — Series 2

Preview — 3 of 10 questions

What is logged, in order?

javascript
function memoize(fn) {
  const cache = new Map();
  return function (n) {
    if (cache.has(n)) {
      console.log('cache hit');
      return cache.get(n);
    }
    const result = fn(n);
    cache.set(n, result);
    return result;
  };
}

let calls = 0;
const square = memoize((n) => {
  calls++;
  return n * n;
});

console.log(square(4));
console.log(square(4));
console.log(calls);
A16, 16, 1
B16, "cache hit", 16, 1
C16, 16, 2
D"cache hit", 16, 16, 1

What is logged?

javascript
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

let initCount = 0;
const init = once(() => {
  initCount++;
  return 'initialized';
});

console.log(init());
console.log(init());
console.log(initCount);
A"initialized", "initialized", 2
B"initialized", undefined, 1
C"initialized", "initialized", 1
DThrows TypeError: fn is not a function on the second call

What is logged?

javascript
const addOne = (x) => x + 1;
const double = (x) => x * 2;

const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);

const transform = pipe(addOne, double);
console.log(transform(3));
A4
B7
CTypeError: fns.reduce is not a function
D8

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.