repeatedly callable fibonacci proxy

by Csaba Hellinger

HTML

Check the console logs for the results.

JavaScript

// wrap state in a proxied function
const wrap = (sum, next) => {
    // blank function, just to make the proxy callable
    const target = () => {};
    // augmenting with state
    target.sum = sum;
    target.next = next;
    // making it coerce into the `sum` value
    target.toString = () => sum.toString();
  	return new Proxy(target, handler);
};

// proxy handler to trap function calls. return new proxy with the next step of the sequence
const handler = {
  	apply: target => wrap(target.sum + target.next, target.next + 1)
};

// function returning the initial state
const f = () => wrap(1, 2);

// tests
console.clear();
console.log(1, f() == 1)          // true
console.log(2, f()() == 3)        // true
console.log(3, f()()() == 6)      // true
console.log(4, f()()()() == 10)   // true

console.log('parseInt', parseInt(f()()()()))   // 10
console.log('toString', f()()()().toString())  // "10"