All quizzesHard
Advanced Functional Patterns — Series 3
Preview — 3 of 10 questions
What is logged?
javascript
const ok = (v) => ({ ok: true, v });
const err = (e) => ({ ok: false, e });
const map = (r, f) => (r.ok ? ok(f(r.v)) : r);
const chain = (r, f) => (r.ok ? f(r.v) : r);
const parse = (s) => (Number.isNaN(Number(s)) ? err('not a number') : ok(Number(s)));
const recip = (n) => (n === 0 ? err('divide by zero') : ok(1 / n));
console.log(JSON.stringify(chain(map(parse('4'), (n) => n - 4), recip)));
console.log(JSON.stringify(chain(parse('x'), recip)));A{"ok":true,"v":0} and {"ok":false,"e":"divide by zero"}
B{"ok":false,"e":"divide by zero"} and {"ok":false,"e":"not a number"}
C{"ok":false,"e":"divide by zero"} and {"ok":false,"e":"divide by zero"}
DBoth throw, because recip is called with a failed result.
What is logged?
javascript
const trampoline = (fn) => (...args) => {
let r = fn(...args);
while (typeof r === 'function') r = r();
return r;
};
const sum = trampoline(function rec(n, acc = 0) {
return n === 0 ? acc : () => rec(n - 1, acc + n);
});
console.log(sum(100000));ARangeError: Maximum call stack size exceeded
Bundefined
CA function object
D5000050000
What is logged?
javascript
const addCPS = (a, b, k) => k(a + b);
const sqCPS = (n, k) => k(n * n);
const out = [];
addCPS(2, 3, (sum) => sqCPS(sum, (sq) => out.push(sum, sq)));
console.log(out.join(','));A5,25
B25,5
C5,10
D(empty) — nothing is logged, since neither function returns a value
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.