开发者

Functional programming: term for filtering then mapping?

Sometimes I find myself wanting to filter a collection, then map the results.

In JavaScript, for example:

var completedStepIds = steps.filter(function(step) {
    return step.isComplete;
}).map(function(step) {
    return step.id;
});

Or in C#/LINQ:

var completedStepIds = 
    from step in steps
    where step.IsComplete
    select step.Id
;

In there a term in functional parlance for this开发者_JAVA技巧 filter-then-map combination?


I guess you want list-comprehensions:

[f(x) | x <- list, g(x)] # Haskell
[f(x) for x in iterable if g(x)] # Python

Well, jQuery's map works this way, which is a list-comprehension in disguise:

> $.map([1,2,3], function(x) { return x != 2 ? 2 * x: null })
[2, 6]

On the other hand Prototype does not filter at all (which is the orthodox thing to do, a map should not reduce):

> [1,2,3].map(function(x) { return x != 2 ? 2 * x: null })
[2, null, 6]

I don't know which library are you using, but you can always write your own abstraction which clears null/undefined from the mapping:

steps.map_and_filter(function(step) {
    return step.isComplete ? step.id : null;
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜