Created
January 29, 2014 18:30
-
-
Save tai2/8693998 to your computer and use it in GitHub Desktop.
From JavaScript: The Good Parts
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
if (typeof Object.inherit === 'undefined') { | |
Object.inherit = function(o) { | |
var F = function() {}; | |
F.prototype = o; | |
return new F(); | |
} | |
} else { | |
throw {'name' : 'Method Duplication', 'message' : 'Object.create already defined'}; | |
} | |
if (typeof Array.dim === 'undefined') { | |
Array.dim = function(dimension, initial) { | |
var a = [], i; | |
for (i = 0; i < dimension; i+= 1) { | |
a[i] = initial; | |
} | |
return a; | |
} | |
} else { | |
throw {'name' : 'Method Duplication', 'message' : 'Object.create already defined'}; | |
} | |
if (typeof Function.prototype.method === 'undefined') { | |
Function.prototype.method = function(name, func, override) { | |
if (override || typeof this.prototype[name] === 'undefined') { | |
this.prototype[name] = func; | |
} | |
return this; | |
}; | |
} else { | |
throw {'name' : 'Method Duplication', 'message' : 'Function.prototype.method already defined'}; | |
} | |
Object.method('superior', function(name) { | |
var that = this; | |
var method = that[name]; | |
return function() { | |
return method.apply(that, arguments); | |
}; | |
}); | |
Number.method('integer', function() { | |
return Math[this < 0 ? 'ceil' : 'floor'](this); | |
}); | |
String.method('trim', function() { | |
return this.replace(/^\s+|\s+$/g, ''); | |
}); | |
Function.method('curry', function() { | |
var slice = Array.prototype.slice; | |
var args = slice.apply(arguments); | |
var that = this; | |
return function() { | |
return that.apply(null, args.concat(slice.apply(arguments))); | |
}; | |
}); | |
Array.method('reduce', function (f, value) { | |
var i; | |
for (i = 0; i < this.length; i++) { | |
value = f(this[i], value); | |
} | |
return value; | |
}); | |
if (typeof is_array === 'undefined') { | |
is_array = function(value) { | |
return value && | |
typeof value === 'object' && | |
typeof value.length === 'number' && | |
typeof value.splice === 'function' && | |
!(value.propertyIsEnumerable('length')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment