user122049 user122049 - 1 month ago 17
Javascript Question

Order of evaluation javascript

I am tasked to write a function f in javascript, and

f(0)+f(1)//should return 0 if evaluated from left to right
//should return 1 if evaluated from right to left


How can I implement the function f? I am thinking about keeping track of whether f is called before, but have no idea how.

The scheme solution is as following:

(define f
(let ((set #f))
(define (fn n)
(if set
0
(begin (set! set #t)
n)))
fn))

Answer

The Scheme solution seems to come down to

var f = (function() {
    var set = false;
    function fn(n) {
        if (set) {
            return 0;
        } else {
            set = true;
            return n;
        }
    }
    return fn;
}());

which is a bit boring but expected. Yes, you need to keep track of the state somewhere outside of f, declaring an extra variable is the simplest solution. It doesn't need to be global though, set is hidden in the scope of the IIFE.

Comments