Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created January 15, 2011 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/780728 to your computer and use it in GitHub Desktop.
Save ryanflorence/780728 to your computer and use it in GitHub Desktop.
Experimental extending of native objects without touching prototypes
;(function(){
function typeOf(item){
if (item._family) return item._family();
return typeof item;
}
Array.prototype._family = function(){ return 'array'; };
var _ = this._ = function(obj){
if (obj._extended) return obj;
var wrapper = {
_obj: obj,
_type: typeOf(obj),
_extended: true,
get: function(){ return wrapper._obj }
};
for (i in exts[wrapper._type]){
if (exts[wrapper._type].hasOwnProperty(i)){
wrapper[i] = function(){
return exts[wrapper._type][i].call(wrapper._obj, [].slice.call(arguments, 0));
}
}
}
return wrapper;
};
var exts = { array: {}, number: {}, string: {} };
_.define = function(type, name, fn){
exts[type][name] = fn;
};
})();
@ryanflorence
Copy link
Author

Example usage: http://jsfiddle.net/rpflorence/DZEPZ/

_.define('array', 'sum', function(){
  var sum = 0;
  for (var i = this.length - 1; i >= 0; i--){
    sum += parseFloat(this[i]);
  };
  return _(sum);
});

_.define('number', 'round', function(precision){
  precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
  return _(Math.round(this * precision) / precision);
});

var value = _([1, 1, 1.5]).sum().round().get(); // => 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment