如何在JavaScript中模拟let表达式?

时间:2018-07-18 17:15:24

标签: javascript ecmascript-6 functional-programming let

请考虑以下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]));  // []

如您所见,它不适用于带有undefined的数组,因为x === undefined不是测试数组是否为空的最佳方法。以下代码可解决此问题:

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

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]));  // [undefined]

但是,写xs[0]xs.slice(1)并不那么优雅。另外,如果您需要多次使用它们,这是有问题的。您要么必须复制代码并进行不必要的额外工作,要么必须创建块作用域,定义常量并使用return关键字。

最好的解决方案是使用let expression。不幸的是,JavaScript没有它们。那么,如何在JavaScript中模拟let表达式?

2 个答案:

答案 0 :(得分:3)

在Lisp中,let expression只是左-左lambda(即immediately-invoked function expression)的语法糖。例如,考虑:

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

; This is syntactic sugar for:

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

在ES6中,我们可以使用arrow functionsdefault parameters创建一个看起来像let表达式的IIFE,如下所示:

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

console.log(z);

使用此技巧,我们可以如下定义take

const take = (n, xxs) =>
    n === 0 || xxs.length === 0 ?
    [] : (([x, ...xs] = xxs) => [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]));  // [undefined]

希望有帮助。

答案 1 :(得分:0)

代替使用IIFE,只需使用具有适当名称的普通函数即可使事情更明确:

const _let = f =>
  f();

const collateBy = f => xs =>
  xs.reduce((m, x) =>
    _let((r = f(x), ys = m.get(r) || []) =>
      m.set(r, (ys.push(x), ys))), new Map());

const includes = t => s =>
  s.includes(t);

xs = ["Dev", "Jeff", "Kalib", "Amy", "Gemma"];

const collation = collateBy(includes("e")) (xs);

console.log(collation.get(true));
console.log(collation.get(false));