阅读 175

Higher-order functions for Swift/Dart/JS

Map

Swift

[1, 2, 3].map { $0 * $0 }
[1, 2, 3].map { value in value * value}
复制代码

flatMap

数组降维

[[1,2,3], [4,5]].flatMap { $0 }  // [1,2,3,4,5]
复制代码

不解包运算可选值

let num: Int? = 8
num.flatMap { $0 * 2 } // Optional(16)
复制代码

compactMap

去除 nil

[1,nil,3].compactMap{ $0 } // [1, 2]
复制代码

Dart

[1, 2, 3].map(((value) => value * value));
复制代码

JavaScript

[1, 2, 3].map(function(value){
    return value * value;
})
    
// ES6
[1, 2, 3].map((value) => value * value);
复制代码

Filter

Swift

[1,2,3].filter { $0 != 2 }
复制代码

Dart

[1, 2, 3].where(((value) => value != 2));
复制代码

JavaScript

[1, 2, 3].filter(function(value){
    return value != 2;
})
    
// ES6
[1, 2, 3].filter((value) => value != 2);
复制代码

Reduce

Swift

[1,2,3].reduce(0, +)
[1,2,3].reduce(0, { initial, next in initial + next })
复制代码

Dart

[1, 2, 3].fold(0, (inital, next) => inital + next);
[1, 2, 3].reduce((inital, next) => inital + next);
复制代码

JavaScript

[1, 2, 3].reduce(function(inital, next) { 
    return inital + next
});

// ES6
[1, 2, 3].reduce((inital, next) => inital + next);
复制代码