Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active August 29, 2015 13:56
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/9233906 to your computer and use it in GitHub Desktop.
Save amatiasq/9233906 to your computer and use it in GitHub Desktop.
Safe extension for native javascript objects

A simple function to extend native object

void extendNative(Function constructor, optional String property, Object methods);

In order to prevent collisions with future standard all extensions are added under a specific property ($ by default), this is configurable by the optional second argument:

extendNative(String, {
  someExtension: function() { }
});
'my string'.$.someExtension();

extendNative(String, 'extensions', {
  anotherExtension: function() { }
});
'my string'.extensions.anotherExtension();

extendNative(String, '_', {
  yetAnotherExtension: function() { }
});
'my string'._.yetAnotherExtension();

Inside the method you have the native value on the this variable:

extendNative(String, {
  startWith: function(start) {
    var beginning = this.substr(0, start.length);
    return beginning === start;
  },
});

And to access extended methods you'll need to access the property:

extendNative(String, {
  startWith: function(start) { ... },
  notStartWith: function(start) {
    return !this.$.startWith(start);
  }
});
//
// STRING
//
extendNative(String, {
startWith: function(start) {
var beginning = this.substr(0, start.length);
return beginning === start;
},
});
'testing'.$.startWith('test'); // true
'testing'.$.startWith('ting'); // false
//
// ARRAY
//
extendNative(Array, {
findIndex: function(iterator) {
var found = -1;
this.some(function(item, index, array) {
if (iterator(item, index, array)) {
found = index;
return true;
}
});
return found;
},
find: function(iterator) {
var index = this.$.findIndex(iterator);
return index === -1 ? null : this[index];
},
});
var future = [ new Date(2013, 00), new Date(2014, 00), new Date(2015, 00) ].$.find(function(item) {
return item > Date.now();
});
console.log(future); // Thu Jan 01 2015 00:00:00 GMT+0100 (CET)
//
// NUMBER
//
extendNative(Number, {
abs: function() { return Math.abs(this) },
round: function() { return Math.round(this) },
});
(-4).abs(); // 4
(4.55).round(); // 4
//
// FUNCTION
//
var toArray = Function.prototype.call.bind([].slice);
extendNative(Function, {
partial: function() {
var self = this;
var fixed = toArray(arguments);
return function() {
var args = toArray(arguments);
self.apply(this, fixed.concat(args));
};
},
});
console.log = console.log.$.partial('LOGGING:');
console.log('testing'); // LOGGING: testing
(function(root) {
'use strict';
function each(object, iterator) {
Object.keys(object).forEach(function(key) {
iterator(object[key], key, object);
});
}
var defaultExtensionName = '$';
var instanceName = '__extensions__';
function extendNative(Constructor, property, methods) {
if (arguments.length === 2) {
methods = property;
property = null;
}
var extensionName = property || defaultExtensionName;
var target = Constructor.prototype;
var alreadyExtended = target.hasOwnProperty(extensionName);
var Extensions = alreadyExtended ?
target[extensionName].constructor :
function Extensions(value) { this.value = value };
each(methods, function(fn, key) {
Extensions.prototype[key] = function() {
fn.apply(this.value, arguments);
};
});
Extensions.prototype.constructor = Extensions;
if (alreadyExtended)
return;
Object.defineProperty(target, extensionName, {
get: function() {
if (this.hasOwnProperty(instanceName))
return this[instanceName];
return this[instanceName] = new Extensions(this);
}
});
}
root.extendNative = extendNative;
})(this);
The MIT License (MIT)
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment