Created
November 5, 2015 09:45
-
-
Save orodio/05a4e68d9402eb374a50 to your computer and use it in GitHub Desktop.
map filter reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr1 = [1, 2, 3, 4, 5]; | |
var arr2 = ["one", "two", "three", "four", "five"]; | |
map | |
[a] -> (a -> b) -> [b] | |
function double (v) { return v + v } | |
var a = arr1.map(double) | |
// a === [2, 4, 6, 8, 10] | |
var b = arr1 | |
.map(double) | |
.map(double) | |
// b === [4, 8, 12, 16, 20] | |
var e = arr2 | |
.map(function (v) { return v.length }) | |
// e === [3, 3, 5, 4, 4] | |
filter | |
[a] -> (a -> Boolean) -> [a] | |
function greaterThan2 (v) { return v > 2 } | |
var c = arr1.filter(greaterThan2) // [3, 4, 5] | |
var d = arr1 | |
.filter(greaterThan2) | |
.map(double) | |
// d === [6, 8, 10] | |
reduce | |
[a] -> (b -> a -> b) -> b -> b | |
var f = arr1.reduce(function (value, v) { return value + v}, 0) | |
// f === 15 | |
value | v | | |
0 | 1 | 1 | |
1 | 2 | 3 | |
3 | 3 | 6 | |
6 | 4 | 10 | |
10 | 5 | 15 | |
function mapper (fn) { | |
return function _mapper (acc, v) { | |
acc.push(fn(v)) | |
return acc; | |
} | |
} | |
var doubler = mapper(double) | |
// function _mapper (acc, v) { | |
// acc.push(double(v)); | |
// return acc; | |
// } | |
var g = arr1.reduce(doubler, []) | |
value | v | eventual return | |
[] | 1 | [2] | |
[2] | 2 | [2, 4] // [2, double(2)] | |
[2, 4] | 3 | [2, 4, 6] // [2, 4, double(3)] | |
[2, 4, 6] | 4 | [2, 4, 6, 8] // [2, 4, 6, double(4)] | |
[2, 4, 6, 8] | 5 | [2, 4, 6, 8, 10] // [2, 4, 6, 8, double(5)] | |
// [2, 4, 6, 8, 10] | |
function filterer (pred) { | |
return function _filterer (acc, v) { | |
if (pred(v)) acc.push(v) | |
return acc; | |
} | |
} | |
var checker = filterer(greaterThan2); | |
// function _filterer (acc, v) { | |
// if (greaterThan2(v)) acc.push(v); | |
// return acc; | |
// } | |
var h = arr1.reduce(checker, []); | |
value | v | return | |
[] | 1 | [] | |
[] | 2 | [] | |
[] | 3 | [3] | |
[3] | 4 | [3, 4] | |
[3, 4] | 5 | [3, 4, 5] | |
// [3, 4, 5] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment