Higher-order functions for Swift/Dart/JS

Map

Swift

[1, 2, 3].map { $0 * $0 }
[1, 2, 3].map { value in value * value}
複製代碼

flatMap

數組降維swift

[[1,2,3], [4,5]].flatMap { $0 }  // [1,2,3,4,5]
複製代碼

不解包運算可選值數組

let num: Int? = 8
num.flatMap { $0 * 2 } // Optional(16)
複製代碼

compactMap

去除 nilui

[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);
複製代碼
相關文章
相關標籤/搜索