2014年10月11日 星期六

[Javascript] MapReduce 用法 (MapReduece Usage)



[].map(callback [, thisArg])

把 A 型態陣列 map 成 B 型態陣列,
回傳的 B 型態陣列長度相同,B 有可能等同於 A。
var callback = function(element, index, context) { /* omitted */ }
第二個參數 thisArg 用來指定 callback 中 this 指到的物件。

Example

var studentFamily = students.map(function(student) {
    return student.family;
});

[].reduce(callback [, initialValue])

把 A 型態陣列 reduce 成 B 資料型態,
回傳的 B 資料型態,型態、大小不定,B 資料型態有可能等同於 A 型態陣列。
var callback = function(previousValue, currentValue, index, context) {/* omitted */ }
第二個參數 initialValue 是第一次跑 callback 時的 previousValue 參數的值,
也就是 previousValue 的最初始值。

Example

var studentFathers = students.map(function(student) {
    return student.family;
}).reduce(function(last, family) {
    return last.concat(family.father);
}, []);

討論

map 的功能用 reduce 也可以做到,但是不建議,因為

如同 Clean Code 這本書內提到的,
function 的命名可以讓看 code 的人一秒鐘理解 function 內處理的事情,

map 是做 mapping,數量不變;
reduce 則是把資料簡化,數量不一定。

參考

Javascript and MapReduce


沒有留言:

張貼留言