简体   繁体   English

填充数组的空白部分,Javascript中的功能方式

[英]Filling the empty part of an array, the functional way in Javascript

I have a function fill defined here: 我在这里定义了一个函数fill

/*
  Takes an Array `array` containing null values, and return a copy of that array, filled with the values in `nArray`:

  Usage:
    fill(
      [1, 2, 3],
      [null, 4, null, 5, null]
    )
    // => [1, 4, 2, 5, 3];
*/
const fill = (nArray, array) => {
  let i = 0;
  return array.map((e) => !e ? nArray[i++] : e);
}

The counter i is defined with let and is not immutable, so this code is not purely functional. 计数器i是用let定义的,并且是不可变的,因此此代码并非纯粹功能。 How would you design this function so it becomes purely functional ? 您将如何设计此功能,使其成为纯粹的功能?

Just make use of shift : 只需使用shift

const fill = (nArray, array) => {
  return array.map((e) => !e ? nArray.shift() : e);
}

EDIT : 编辑:

Note also, that you will have to check that nArray is not empty, for example : 还要注意,您将必须检查nArray是否为空,例如:

(!e && nArray.length > 0) ? nArray.shift() : e

Unless you expect map to be some weird function (not the typical Array.prototype one) where that impure callback would cause havoc, your code is totally fine. 除非您期望map是一些奇怪的函数(而不是典型的Array.prototype ),否则不纯的回调会造成严重破坏,否则您的代码就可以了。 i is not observable from the outside world, which makes your function pure. i无法从外界观察到,这使您的功能纯净。

If you want to avoid all mutation at any cost, you should basically go for a recursive approach: 如果您想不惜一切代价避免所有变异,则基本上应该采用递归方法:

const fill = (nArray, array) =>
  array.length
  ? array[0] 
    ? [array[0]].concat(fill(nArray, array.slice(1)))
    : [nArray[0]].concat(fill(nArray.slice(1), array.slice(1)))
  : []

(which is horribly inefficient of course, given JavaScript's lack of cons lists) (考虑到JavaScript缺少缺点列表,这无疑是非常低效的)

You can also use a more declarative implementation of the same thing: 您还可以对同一事物使用更具声明性的实现:

const fill = (nArray, array) => {
  if (!array.length) return [];
  const [a, ...as] = array;
  if (a) return [a, ...fill(nArray, as)];
  const [b, ...bs] = nArray;
  return [b, ...fill(bs, as)];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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