[英]Lazily map, filter, reduce, etc. in JavaScript
Array#map
, Array#filter
create a new array and hence effectively iterating over the array (or creating new array). Array#map
, Array#filter
创建一个新数组,从而有效地迭代数组(或创建新数组)。
Whereas in rust, python, java, c#, etc. such expression chain will iterate only once.而在 rust、python、java、c# 等表达式中只会出现一次。
In most cases this is irrelevant and we do not have to care about that.在大多数情况下,这无关紧要,我们不必关心这一点。 However in some cases the performance hit could be a deal breaker to leverage the function api of the
Array
class.然而,在某些情况下,性能损失可能会破坏交易,以利用
Array
class 的 function api。
How do you mitigate this?你如何减轻这种情况? So you have any preference on a library enabling lazy evaluation for functional expression?
所以你对函数表达式启用惰性求值的库有什么偏好吗?
If you don't want it to iterate more than once.如果您不希望它多次迭代。 You can use a loop
您可以使用循环
const numbers = [1,2,3,4,5,6]
let result = 0;
for(const number of numbers) {
const square = number * number
if(square % 2) {
result += square
}
}
console.log(result)
Or reduce或减少
const numbers = [1,2,3,4,5,6]
const result = numbers.reduce((acc, number) => {
const square = number * number
if(square % 2) {
return acc + square
}
return acc
}, 0)
console.log(result)
Array methods aren't functional so the whole premise is flawed.数组方法不起作用,所以整个前提是有缺陷的。 The fact that they exist on the array object means they aren't open composition the way pure functions are.
它们存在于数组 object 上的事实意味着它们不像纯函数那样开放组合。 You can get closer though
虽然你可以靠近
const square = (n) => n * n
const oddNumberOrZero = (n) => n % 2 ? n : 0
const add = (a, b) => a + b
const addOddSquare = (a, b) => add(a, oddNumberOrZero(square(b)))
const reduce = (arr, fn, acc) => arr.reduce(fn,acc)
const numbers = [1,2,3,4,5,6]
const result = reduce(numbers, addOddSquare, 0)
console.log(result)
You also seem to be conflating fluent interfaces with functional programming.您似乎也将流畅的接口与函数式编程混为一谈。
I believe what you are looking for is processing the array as a stream.我相信您正在寻找的是将阵列处理为 stream。 You can do that with highland :
你可以用highland做到这一点:
import _ from "highland";
_([1, 2, 3, 4])
.filter(v => v % 2 === 0)
.map(v => v * 2)
.toArray((result: number[]) => {
// result is the new array
});
Relevant part from the docs :文档中的相关部分:
Arrays - Streams created from Arrays will emit each value of the Array (...)
Arrays - 从 Arrays 创建的流将发出数组的每个值 (...)
Please check the following code lines.请检查以下代码行。 In the code, in which v * v is divided 2 means that v is divided.
代码中,其中v * v被除2表示v被除。
const numbers = [1,2,3,4,5,6]; const res = numbers.reduce((sum, v)=> sum + (v % 2? v * v: 0), 0); console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.