prototype/src/lang/function.js

89 lines
2.3 KiB
JavaScript
Raw Normal View History

2008-12-11 10:49:41 +00:00
Object.extend(Function.prototype, (function() {
var slice = Array.prototype.slice;
function update(array, args) {
var arrayLength = array.length, length = args.length;
while (length--) array[arrayLength + length] = args[length];
return array;
}
function merge(array, args) {
array = slice.call(array, 0);
return update(array, args);
}
function argumentNames() {
2008-12-11 10:42:15 +00:00
var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
.replace(/\s+/g, '').split(',');
return names.length == 1 && !names[0] ? [] : names;
2008-12-11 10:49:41 +00:00
}
function bind(context) {
2008-12-11 10:42:15 +00:00
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
2008-12-11 10:49:41 +00:00
var __method = this, args = slice.call(arguments, 1);
2008-12-11 10:42:15 +00:00
return function() {
2008-12-11 10:49:41 +00:00
var a = merge(args, arguments);
return __method.apply(context, a);
2008-12-11 10:42:15 +00:00
}
2008-12-11 10:49:41 +00:00
}
function bindAsEventListener(context) {
var __method = this, args = slice.call(arguments, 1);
2008-12-11 10:42:15 +00:00
return function(event) {
2008-12-11 10:49:41 +00:00
var a = update([event || window.event], args);
return __method.apply(context, a);
2008-12-11 10:42:15 +00:00
}
2008-12-11 10:49:41 +00:00
}
function curry() {
2008-12-11 10:42:15 +00:00
if (!arguments.length) return this;
2008-12-11 10:49:41 +00:00
var __method = this, args = slice.call(arguments, 0);
2008-12-11 10:42:15 +00:00
return function() {
2008-12-11 10:49:41 +00:00
var a = merge(args, arguments);
return __method.apply(this, a);
2008-12-11 10:42:15 +00:00
}
2008-12-11 10:49:41 +00:00
}
2008-12-11 10:42:15 +00:00
2008-12-11 10:49:41 +00:00
function delay(timeout) {
var __method = this, args = slice.call(arguments, 1);
timeout = timeout * 1000
2008-12-11 10:42:15 +00:00
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
2008-12-11 10:49:41 +00:00
}
function defer() {
var args = update([0.01], arguments);
2008-12-11 10:42:15 +00:00
return this.delay.apply(this, args);
2008-12-11 10:49:41 +00:00
}
function wrap(wrapper) {
2008-12-11 10:42:15 +00:00
var __method = this;
return function() {
2008-12-11 10:49:41 +00:00
var a = update([__method.bind(this)], arguments);
return wrapper.apply(this, a);
2008-12-11 10:42:15 +00:00
}
2008-12-11 10:49:41 +00:00
}
function methodize() {
2008-12-11 10:42:15 +00:00
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
2008-12-11 10:49:41 +00:00
var a = update([this], arguments);
return __method.apply(null, a);
2008-12-11 10:42:15 +00:00
};
}
2008-12-11 10:49:41 +00:00
return {
argumentNames: argumentNames,
bind: bind,
bindAsEventListener: bindAsEventListener,
curry: curry,
delay: delay,
defer: defer,
wrap: wrap,
methodize: methodize
}
})());