JavaScript是否有像.NET LINQ这样的延迟收集API?

w3nuxt5m  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(86)

我知道JavaScript Array有mapfilter等,reduce可以用来合并它们(虽然我真的不喜欢语法,但它确实有效)。但是,下面一个简单的例子可以证明它是延迟的(即在函数调用时立即执行)。
然而,在C#中,像WhereSelect这样的LINQ函数实际上并不执行表达式,直到需要它,并且(据我所知)只有最终的集合被分配:

var a = new int[] { 1, 2, 3 };

var b = a.Where(q => q < 2).Select(q => q + 1); // This code is not actually executed here yet
var c = b.ToArray(); // Here an array is actually allocated

// c should be [ 2 ]

在下面的JavaScript中,我相信实际上分配了两个数组,并且立即调用了表达式:

const a = [1,2,3];

const b = a.filter(q => { 
  console.log("filter executed");
  return q < 2;
});
console.log(b.constructor.name);

const c = b.map(q => {
  console.log("map executed")
  return q + 1;
});
console.log(c.constructor.name);
// c should be [ 2 ]

我能找到的最接近的是yield operator,但我找不到任何内置方法将数组转换为这样的集合/生成器。
假设我有一个大的数组/集合,是否有任何内置函数可以延迟执行,直到实际需要它们?
有时候,一个操作可以像这样(只是一个例子),延迟执行可能更有利:

var foo = bar.filter(pred1).map(q => calc(q.value)).filter(q => Boolean(q)).map(finalMap);

下面是一个例子(但是在这个过程中分配了4个数组):

const adjustedMultiplier = [1, 1.2, 1.5, 1.7];

const data = [
  {
    name: "Person 1",
    fromId: 1,
    score: 9,
    details: {} // More data
  },
  {
    name: "Person 2",
    fromId: 1,
    score: 6,
    details: {} // More data
  },
  {
    name: "Person 3",
    fromId: 3,
    score: 8,
    details: {} // More data
  },
  // More
];

const expectedResult = data
  .filter(q => q.fromId < 3)
  .map(q => ({
    name: q.name,
    adjustedScore: q.score * adjustedMultiplier[q.fromId]
  }))
  .filter(q => q.adjustedScore >= 8);
console.log(expectedResult);
qlvxas9a

qlvxas9a1#

如果我理解正确的话,你在寻找一个高阶函数。在这种情况下,您也可以探索关闭。在下面的代码中,创建了一个返回另一个函数的函数。您可以调用内部函数whith数据,并在需要时执行它

const adjustedMultiplier = [1, 1.2, 1.5, 1.7];

const data = [{
    name: "Person 1",
    fromId: 1,
    score: 9,
    details: {} // More data
  },
  {
    name: "Person 2",
    fromId: 1,
    score: 6,
    details: {} // More data
  },
  {
    name: "Person 3",
    fromId: 3,
    score: 8,
    details: {} // More data
  }
];

function deferFn() {
  return function(val) {
    return data
      .filter(q => q.fromId < 3)
      .map(q => ({
        name: q.name,
        adjustedScore: q.score * adjustedMultiplier[q.fromId]
      }))
      .filter(q => q.adjustedScore >= 8);
  }

}
const expectedResult = deferFn()
console.log(expectedResult); // this will not execute the function
console.log(expectedResult(data)) // this will execute the function
pobjuy32

pobjuy322#

try this

var result = a.filter(x=>x<2).map(x=>x+1)

Refer this [link][1]

相关问题