Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Last active March 29, 2017 21:31
Show Gist options
  • Save miguel-leon/6d53d76a5f873245629a36e051b992fb to your computer and use it in GitHub Desktop.
Save miguel-leon/6d53d76a5f873245629a36e051b992fb to your computer and use it in GitHub Desktop.
Few JS functions
/**
* Extends `obj` with properties created as `key: value` for every pair of two consecutive arguments
* @param {Object} obj
* @return {Object} obj
*/
function extendWithArgs(obj) {
for (var i = 2; i < arguments.length; i += 2) {
obj[arguments[i-1]] = arguments[i];
}
return obj;
}
/**
* Creates an object as if using `new ctor()` but passing the arguments as an `Array`
* @param {Function} ctor
* @param {Array} args
* @return {Object} new object of constructor ctor
*/
function constructorApply(ctor, args) {
var obj = Object.create(ctor.prototype);
ctor.apply(obj, args);
return obj;
}
/**
* @method String.prototype.interpolate(...)
* Interpolates a string.
* @param {string...} arguments to interpolate
* @returns {string}
*/
if (!String.prototype.interpolate) {
Object.defineProperty(String.prototype, 'interpolate', {
enumerable: false,
value: function interpolate() {
var args = arguments;
return this.replace(/\{\d+\}/g, function(match) {
return args[+match.slice(1, -1)];
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment