简体   繁体   中英

Why is (_=1)=>$=>_++ a counter

A friend got this question at a Javascript job interview:

Explain how this counter works (In other word, what is the non minimified version)

  let Counter = (_=1)=>$=>_++ let c1 = Counter() console.log(c1()) //1 console.log(c1()) //2 

This is the same as

const Counter = function(counter = 1) {
  return function count() {
    return counter++;
  };
}

So basically when you call Counter() it incapsulates counter with 1 as default value and every time you are calling count function returned by it, it returns counter value and increases it by 1

(_=1)=>$=>_++

This is function that uses arrow syntax, it's equal to

function f(_ = 1) {
    return $ => _++;
}

$ => _++; is also arrow function, it captures closure _ , incerements it and returns (postfix increment, so in fact it returns value and later increments it):

function f(_ = 1) {
    return function($) { return _++; };
}

So the code is equal to

function Counter(count = 1) {
    return function() { return count++; };
}

(renamed _ to count and removed redundant $ variable)

Function Counter will return previous value + 1 each time, starting from count value, like counter does

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM