pjb3 (owner)

Revisions

gist: 126211 Download_button fork
public
Public Clone URL: git://gist.github.com/126211.git
Embed All Files: show embed
enumerable.js #
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
Array.prototype.each = function(f) {
  for(var i = 0; i < this.length; i++) {
    f(this[i])
  }
}
 
Array.prototype.eachWithIndex = function(f) {
  var i = 0;
  this.each(function(e){
    f(e, i++)
  })
}
 
Array.prototype.collect = function(f) {
  var a = []
  this.each(function(e){
    a.push(f(e))
  })
  return a
}
Array.prototype.map = Array.prototype.collect
 
Array.prototype.inject = function(init, f) {
  var r, argc = arguments.length
  argc == 1 ? f = init : r = init
  this.eachWithIndex(function(e,i){
    r = (i == 0 && argc == 1) ? e : f(r, e)
  })
  return r
}
 
var a = [1,2,3]
 
a.each(function(e){ print(e) })
 
a.eachWithIndex(function(e, i){
  print(i+' -> '+e)
})
 
function square(e){
  return e * e
}
print(a.map(square))
 
var bigArray = []
for(var i = 0; i < 10000; i++) {
  bigArray.push(i)
}
 
print(bigArray.inject(0, function(acc,e){
  return acc + e
}))
 
print(bigArray.inject(function(acc,e){
  return acc + e
}))