Behavioral Patterns — Series 3

Preview — 3 of 10 questions

What is logged?

javascript
const bus = {
  parts: {},
  register(name, part) { this.parts[name] = part; part.bus = this; },
  notify(from, ev) {
    for (const [name, part] of Object.entries(this.parts)) {
      if (name !== from) part.receive(from, ev);
    }
  },
};

const log = [];
bus.register('a', { receive: (f, e) => log.push(`a<-${f}:${e}`) });
bus.register('b', { receive: (f, e) => log.push(`b<-${f}:${e}`) });

bus.notify('a', 'ping');
console.log(log.join(' | '));
Aa<-a:ping | b<-a:ping
Bb<-a:ping
Ca<-a:ping
D(empty)

What is logged?

javascript
const num = (v) => ({ type: 'num', v });
const add = (l, r) => ({ type: 'add', l, r });

const evaluate = { num: (n) => n.v, add: (n, visit) => visit(n.l) + visit(n.r) };
const print    = { num: (n) => String(n.v), add: (n, visit) => `(${visit(n.l)}+${visit(n.r)})` };

const walk = (visitor) => { const visit = (n) => visitor[n.type](n, visit); return visit; };

const tree = add(num(1), add(num(2), num(3)));
console.log(walk(evaluate)(tree), walk(print)(tree));
A6 6
B1+2+3 (1+(2+3))
C6 1+2+3
D6 (1+(2+3))

What is logged?

javascript
const tokens = '3 4 + 2 *'.split(' ');
const stack = [];

for (const t of tokens) {
  if (/^\d+$/.test(t)) stack.push(Number(t));
  else {
    const b = stack.pop();
    const a = stack.pop();
    stack.push(t === '+' ? a + b : a * b);
  }
}

console.log(stack[0], stack.length);
A14 1
B11 1
C9 2
D14 3

Sign up free to play

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