JavaScript:如何处理所有随后的元素对?

时间:2019-03-12 17:41:46

标签: javascript lambda functional-programming reduce

我有一个单词数组:

["get", "out", "of", "the", "way"]

和一个功能

isPrepOrParticle
为元素“ out” “ of” 返回 true

我想用下划线将所有 true 元素粘合到以前的元素,并获得以下信息:

["get_out_of", "the", "way"]

有没有一种很好的功能性方法,可以通过对所有随后的元组应用某种功能来做到这一点:

f = (a, b) => {
  if (isPrepOrParticle(b)) return a + "_" + b;

  return null;
}

3 个答案:

答案 0 :(得分:2)

我相信reduceRight也提供了一种纯粹的功能性方法来实现此目的:

const merge = (words, preps) =>
    words.reduceRight(([b, ...rest], a, i) => 
        preps.has(words[i+1]) ? [a+"_"+b, ...rest] : b ? [a, b, ...rest] : [a], []);

console.log(merge(["get", "out", "of", "the", "way"], new Set(["out", "of"])));

答案 1 :(得分:1)

如果您想要经典的递归解决方案,它可能看起来像这样:

const isPrepOrParticiple = word => word === 'out' || word === 'of';

function glue(a, b, ...rest) {
  if (a) {
    if (b) {
      if (isPrepOrParticiple(b)) {
        return glue(`${a}_${b}`, ...rest);
      }
      return [a, ...glue(b, ...rest)];
    }
    return [a];
  }
  return [];
}

const input = ['get', 'out', 'of', 'the', 'way'];

console.log(glue(...input));

答案 2 :(得分:1)

这是补充约旦程序的另一个经典递归定义。它是使用表达式而不是语句写的-

const glue = (a = "", b = "", ...rest) =>
  b === ""                      // base: no b
    ? [ a ]
: a === ""                      // inductive: some b, no a
    ? []
: isPrepOrParticiple (b)        // inductive: some b, some a, participle
    ? glue (`${a}_${b}`, ...rest)
: [ a, ...glue (b, ...rest) ]   // inductive: some b, some a, non-participle

const isPrepOrParticiple = word =>
  word === 'out' || word === 'of'

console .log (glue ('get', 'out', 'of', 'the', 'way'))
// [ 'get_out_of', 'the', 'way' ]