[英]underscore or lazy.js map (0,1,2,3,4) + (1,2,3,4,5) ->(1,3,5,7,9)
I want to map a sequence to another sequence such as 我想将一个序列映射到另一个序列,例如
map (0,1,2,3,4) + (1,2,3,4,5) -> (1,3,5,7,9) 映射(0,1,2,3,4)+(1,2,3,4,5)->(1,3,5,7,9)
How to do that in lazy.js or underscore ? 如何在lazy.js或下划线中做到这一点 ?
Thanks! 谢谢!
You can use _.zip
and _.map
, like this 您可以像这样使用
_.zip
和_.map
var _ = require("underscore");
function sum(numbers) {
var result = 0;
for (var i = 0; i < numbers.length; i += 1) {
result += numbers[i];
}
return result;
}
console.log(_.map(_.zip([0, 1, 2, 3, 4], [1, 2, 3, 4, 5]), sum))
// [ 1, 3, 5, 7, 9 ]
Since only two numbers are going to be there, always, you can simplify that like this 由于只有两个数字,所以总是可以这样简化
var result = _.chain([0, 1, 2, 3, 4])
.zip([1, 2, 3, 4, 5])
.map(function(numbers) {
return numbers[0] + numbers[1];
})
.value();
console.log(result);
You can make it a little more generic and clean, like this 您可以像这样使它更通用,更干净
function sum(numbers) {
return numbers.reduce(function(result, current) {
return result + current;
}, 0);
}
var result = _.chain([0, 1, 2, 3, 4])
.zip([1, 2, 3, 4, 5])
.map(sum)
.value();
Or even simpler, like in the first answer 甚至更简单,例如第一个答案
console.log(_.map(_.zip([0, 1, 2, 3, 4], [1, 2, 3, 4, 5]), sum));
The above example can be achieved in the following way using underscore: 可以使用下划线通过以下方式实现以上示例:
_.map([0, 1, 2, 3, 4], function(n, i) {
return n + i + 1
}) // This returns [1, 3, 5, 7, 9]
Here's a link to the API docs: Underscore#map 这是API文档的链接: Underscore#map
Using underscore, @thefortheye's solution works well, here's a similar solution just using lazy.js instead; 使用下划线,@ thefortheye的解决方案效果很好,这是一个类似的解决方案,只是使用了lazy.js ;
> var Lazy = require('lazy.js');
> var addParts = function(x) { return Lazy(x).sum(); }
> Lazy([0,1,2,3,4]).zip([1,2,3,4,5]).map(addParts).toArray()
[ 1, 3, 5, 7, 9 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.