Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active December 13, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amatiasq/4987642 to your computer and use it in GitHub Desktop.
Save amatiasq/4987642 to your computer and use it in GitHub Desktop.
How to dominate Javascript's world
(function extensions() {
function arr(val) {
return Array.prototype.slice.call(val);
}
function extend(Type, prototype) {
function E(val) { this.val = val }
E.prototype = prototype;
prototype.constructor = E;
Type.prototype.ext = function() { return new E(this) };
}
extend(Function, {
bindArgs: function(var_args) {
var self = this;
var binded = arr(arguments);
return function() {
return self.apply(this, binded.concat(arr(arguments)));
};
},
bindArg: function(index, value) {
var self = this;
return function() {
var args = arr(arguments);
args.splice(index, 0, value);
return self.apply(this, args);
};
},
rest: function(from) {
from = from || 0;
var self = this;
return function() {
var args = arr(arguments);
if (from === 0)
return self.call(this, args);
var result = args.splice(0, from);
result.push(args.splice(from);
return self.apply(this, result);
};
}
});
extend(String, {
startsWith: function(start) {
return this.val.substr(0, start.length) === start;
},
endsWith: function(end) {
return this.val.substr(-end.length) === end;
},
repeat: function(times, separator) {
var result = [];
for (var i = times; i--; )
result[i] = this.val;
return result.join(separator || '');
}
});
extend(Object, {
each: function(args) {
args.shift(this.val);
return _.each.apply(_, args);
}.ext().rest(),
});
extend(Array, {
first: function() {
return this.val.length ? this.val[0] : null;
},
last: function() {
return this.val.length ? this.val[this.val.length - 1] : null;
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment