/ javascript

Javascript order of evaluation

Sometimes I get confused which statement is evaluated first.

Remember that order starts within the () first and move outwards.
Eg.
console.log(func3(func2(func1()))
will be called in the order, func1(), func2(), func3().

JSBin: https://jsbin.com/kikibul/edit?js,console

function avg(arr) {
  return arr.reduce((a,b)=> a+b) /arr.length;
}

a = [1,2,3];
console.log(avg(a.map(a=>a*2))); // is the same as avg([2,4,6])
console.log(avg([1,2,3]));

Curry functions

Update: May 16, 2018 12:20 PM, Wednesday

Thought I'll add curry functions here since the order of evaluation is from left to right, which is opposite of nested functions.

JSBin: https://jsbin.com/siriqif/edit?js,console

// Currying
// https://hackernoon.com/currying-in-js-d9ddc64f162e

function curry(fn) {
  return (x) => {
    console.log('sum(x): ',x)
    return (y) => {
      console.log('sum(x)(y): ', y)
      return (z) => {
        console.log('sum(x)(y)(z): ', fn(x,y,z))
        return fn(x, y, z)
      };
    };
  };
} 

const sum3 = curry((x,y,z) => {
  return x+y+z
})

sum3(1)
console.log('---------------')

setTimeout(function(){sum3(1)(2); console.log('---------------') }, 5000)

setTimeout(function(){sum3(1)(2)(3); console.log('---------------')}, 10000)