Skip to content

Instantly share code, notes, and snippets.

@stevegraham
Created June 7, 2011 17:18
Show Gist options
  • Select an option

  • Save stevegraham/1012673 to your computer and use it in GitHub Desktop.

Select an option

Save stevegraham/1012673 to your computer and use it in GitHub Desktop.
side-effect free js
var Enumerable = function() {
this.map = function(func, i, m) {
var idx = i || 0
var mem = m || []
if(this.length != idx) {
return this.map(func, idx+1, mem.concat(func(this[idx])))
} else {
return mem
}
}
this.each = function(func,i) {
var idx = i || 0
if(this.length != idx) {
func(this[idx])
this.each(func, idx+1)
}
return this
}
this.select = function(func, i, m) {
var idx = i || 0
var mem = m || []
if(this.length != idx) {
if(func(this[idx]) != false) {
return this.select(func, idx+1, mem)
} else if(idx==0) {
return this.slice(1,this.length+1).select(func)
} else {
return this.select(func, idx+1, this.slice(0,idx).concat(this.slice(idx+1,this.length)))
}
} else {
return mem
}
}
this.first = function(end) {
if(typeof(end) != 'number') {
return this[0]
} else {
return this.slice(0,end)
}
}
this.last = function() {
return this[this.length-1]
}
this.compact = function(func,i) {
this.select(function(i) { return i })
}
};
Function.prototype.extend = function(module) {
module.apply(this.prototype)
}
Array.extend(Enumerable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment