Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

ecmascript 6 - How to simulate let expressions in JavaScript?

Consider the following implementation of take:

const take = (n, [x, ...xs]) =>
    n === 0 || x === undefined ?
    [] : [x, ...take(n - 1, xs)];

console.log(take(7, [1, 2, 3, 4, 5])); // [1, 2, 3, 4, 5]
console.log(take(3, [1, 2, 3, 4, 5])); // [1, 2, 3]
console.log(take(1, [undefined, 1]));  // []
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Lisp, a let expression is just syntactic sugar for a left-left lambda (i.e. an immediately-invoked function expression). For example, consider:

(let ([x 1]
      [y 2])
  (+ x y))

; This is syntactic sugar for:

((lambda (x y)
    (+ x y))
  1 2)

In ES6, we can use arrow functions and default parameters to create an IIFE that looks like a let expression as follows:

const z = ((x = 1, y = 2) => x + y)();

console.log(z);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...