如何在映射时合并两个数组?

问题描述 投票:2回答:3

背景:我对Ramda和FP很新。我发现自己遇到了这种情况,我有两个输入itemListcostList。列表中的值具有基于idx的关系。所以itemList[0]costList[0]代表可能在同一个对象中的值(例如{ item: itemList[0], cost: costList[0]})。因此,替代解决方案可以从合并itemList和costList开始。我对其中一种或两种解决方案感兴趣。任何其他提示和建议也将受到赞赏。

  let itemList = ['shirt', 'shoes'];
  let costList = ['shirtCost', 'shoesCost'];

  let formulaList = R.map(
    x => ({
      formulaXAttr: x,
      formulaYAttr: 'tbd later',
    })
  )(itemList);

  let finalList = R.map(
    x => R.merge(x, {formulaYAttr: '???'})  // how to merge in costList?
  )(formulaList);

  // this is how i'd do it in vanilla JS
  let finalList = formulaList.map((x, idx) => ({
    ...x,
    formulaYAttr: costList[idx],
  }));
functional-programming ramda.js
3个回答
3
投票

你在Ramda中寻找的函数叫做zipWith,它接受一个期望两个参数的函数,一个用于第一个列表的每个元素,另一个用于第二个列表中的成对元素。这最终只是一个列表,它与两个提供的列表中的较短者一样长,包含为每对调用函数的结果。

const itemList = ['shirt', 'shoes'];
const costList = ['shirtCost', 'shoesCost'];

const fn = R.zipWith((x, y) =>
  ({ formulaXAttr: x, formulaYAttr: y }))

console.log(
  fn(itemList, costList)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

2
投票

斯科特克里斯托弗的回答显然是正确的。 zipWith正是为这种情况而设计的。在标题中,您会在映射时询问如何执行此操作。我想指出的是,虽然Ramda确实为此提供了一个选项(详见addIndex),但通常不赞成。其原因对于更多地了解FP非常重要。

map的一种理解是,它通过将给定函数应用于每个元素,将一种类型的元素列表转换为另一种类型的元素列表。这是一个很好的公式,但有一个更通用的方法:map通过将给定函数应用于每个元素,将一种类型的元素的容器转换为另一种类型的元素的容器。换句话说,mapping的概念可以应用于许多不同的容器,而不仅仅是列表。 FantatsyLand规范为具有map方法的容器定义了一些规则。具体类型是Functor,但对于那些没有相关数学背景的人,这可以被认为是Mappable。 Ramda应该与这些类型很好地互操作:

const square = n => n * n;
map(square, [1, 2, 3, 4, 5])  //=> [1, 4, 9, 16, 25]


// But also, if MyContainer is a Functor
map(square, MyContainer(7)) //=> MyContainer(49)


// and, for example, if for some Maybe Functor with Just and Nothing subtypes
const {Just, Nothing} = {Maybe}
// then
map(square, Just(6)) //=> Just(36)
map(square, Nothing()) //=> Nothing()

Ramda的map函数只使用容器的元素调用提供的转换函数。它不提供索引。这是有道理的,因为并非所有容器都有任何索引概念。

因此,映射是Ramda不是尝试匹配索引的地方。但这是Ramda的three zip functions的核心。如果你想组合两个元素与索引相匹配的列表,你最简单的就像Scott和zipWith一样。但你也可以使用zip,它的工作原理如下:

zip(['a', 'b', 'c', 'd'], [2, 3, 5, 7]) //=> [['a', 2], ['b', 3], ['c', 5], ['d', 7]]

然后在结果对上调用mapzipWith只需让您一步完成相同的操作。但如果没有它,像mapzip这样的原始人仍然可以结合起来做你喜欢的事。


2
投票

为了配合其他答案,我想告诉你如何自己写这种东西。 Ramda库并不总是为您提供单行解决方案,如果您将解决方案限制为仅使用Ramda提供的功能,您就会退缩。

这种做法将使您有信心尝试编写自己的程序。当/如果您发现Ramda具有您需要的某些功能,您可以轻松地重构您的程序以使用Ramda提供的功能。

const None =
  Symbol ()

const zipWith = (f, [ x = None, ...xs ], [ y = None, ...ys ]) =>
  x === None || y === None
    ? []
    : [ f (x, y) ] .concat (zipWith (f, xs, ys))

console.log
  ( zipWith
      ( (name, price) => ({ name, price })
      , [ 'shoes', 'pants' ]
      , [ 19.99, 29.99 ]
      )
  )

// [ { name: "shoes", price: 19.99 }
// , { name: "pants", price: 29.99 }
// ]

上面使用的解构赋值创建有助于维护声明式样式,但它确实创建了不必要的中间值。下面,我们使用额外的状态参数i来显着减少内存占用。

const zipWith = (f, xs, ys, i = 0) =>
  i >= xs.length || i >= ys.length
    ? []
    : [ f (xs[i], ys[i]) ] .concat (zipWith (f, xs, ys, i + 1))
    
console.log
  ( zipWith
      ( (name, price) => ({ name, price })
      , [ 'shoes', 'pants' ]
      , [ 19.99, 29.99 ]
      )
  )
  
// [ { name: "shoes", price: 19.99 }
// , { name: "pants", price: 29.99 }
// ]

注意两种实现都是纯粹的。没有副作用。输入不会发生变化,并且始终为输出构造新的Array。

我们的实现也是完全的,因为当提供有效输入时,它总是以有效输出响应。

console.log
  ( zipWith
      ( (name, price) => ({ name, price })
      , [ 'shoes' ]
      , [ 19.99 ]
      )
      // [ { name: "shoes", price: 19.99 } ]

  , zipWith
      ( (name, price) => ({ name, price })
      , [ 'shoes' ]
      , []
      )
      // []

  , zipWith
      ( (name, price) => ({ name, price })
      , []
      , [ 19.99 ]
      )
      // []

  , zipWith
      ( (name, price) => ({ name, price })
      , []
      , []
      )
      // []
  )

这次Ramda背对着R.zipWith,但下次可能不会。然而,没有恐惧,因为你得到了这个!一旦你意识到编程没有魔力就很容易编写这样的程序。如果你遇到困难,我想总会有StackOverflow。

© www.soinside.com 2019 - 2024. All rights reserved.