-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.js
More file actions
77 lines (72 loc) · 1.9 KB
/
func.js
File metadata and controls
77 lines (72 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
window.MBO = {};
// Some library stuff, created mostly for fun
// Call @fun@ with @element@ and @i@
//
// Ex.
// var sum = 0;
// MBO.each([1,2,3], function(el) { sum += el });
// # sum === 6
//
// Asign @this@ to @caller@
MBO.each = function each(collection, fun) {
var i;
for (i = 0; i < collection.length; i++) {
fun.apply(each.caller, [collection[i], i]);
}
};
// Call @fun@ with @element@ and @i@ and take add returned value
// to result collection
//
// Returns new collection containing results from calling @fun@
//
// Ex.
// MBO.map([1,2,3], function(el) { return el * 2 });
// #=> [2,4,6]
//
// Asign @this@ to @caller@
MBO.map = function map(collection, fun) {
var i, result;
result = []
for (i = 0; i < collection.length; i++) {
result.push(fun.apply(map.caller, [collection[i], i]));
}
return result;
};
// Call @fun@ with @element@ and @i@ and take only those elements from
// original collection, which @fun@ returned truthly value for
//
// Returns colleciton with values not filtered by fun
//
// Ex.
// MBO.grep([1,2,3], function(el) { return el >= 2 });
// #=> [2,3]
//
// Asigns @this@ to @caller@
MBO.grep = function grep(collection, fun) {
var i, result, tmp;
result = [];
for (i = 0; i < collection.length; i++) {
if (fun.apply(grep.caller, [collection[i], i])) {
result.push(collection[i]);
}
}
return result;
};
// Call @fun@ with @result@, @element@ and @i@ and take returend value
// as next result,
//
// Returns last result returned from func
//
// Ex.
// MBO.reduce([1,2,3], 0, function(sum, el) { return sum + el });
// #=> 6
//
// Asigns @this@ to @caller@
MBO.reduce = function reduce(collection, initial, fun) {
var i, result;
result = initial;
for (i = 0; i < collection.length; i++) {
result = fun.apply(reduce.caller, [result, collection[i], i]);
}
return result;
};