Skip to content

Instantly share code, notes, and snippets.

@peizguo
Last active September 26, 2017 15:26
Show Gist options
  • Select an option

  • Save peizguo/30dd1d6bc99afca9f7c62f8e954667d3 to your computer and use it in GitHub Desktop.

Select an option

Save peizguo/30dd1d6bc99afca9f7c62f8e954667d3 to your computer and use it in GitHub Desktop.
JavaScript Number Extension for more object-oriented expression
(function(global) {
"use strict";
let log = global.console && global.console.log || function(){};
function extend(target, source) {
for(var prop in source) {
if(source.hasOwnProperty(prop)) {
if(typeof(target[prop]) !== "undefined") {
target["_origin_" + prop] = target[prop];
log("Renamed target." + prop);
}
target[prop] = source[prop];
log("Assigned target." + prop + " from source." + prop);
}
}
}
function alias(target, methods) {
methods.forEach(function(pair) {
let existing = pair[1],
newName = pair[0];
if(typeof(target[existing]) !== 'undefined') {
target[newName] = target[existing];
}
});
}
extend(Number.prototype, {
seconds: function() {
return this * 1000;
},
minutes: function() {
return this * (60).seconds();
},
hours: function() {
return this * (60).minutes();
},
days: function() {
return this * (24).hours();
},
weeks: function() {
return this * (7).days();
},
months: function() {
return this * (30).days();
},
years: function() {
return this * (365).days();
},
ago: function() {
return new Date(new Date() - this);
},
fromNow: function() {
return new Date(new Date() + this);
}
});
alias(Number.prototype, [
['second', 'seconds'],
['minute', 'minutes'],
['hour', 'hours'],
['day', 'days'],
['week', 'weeks'],
['month', 'months'],
['year', 'years']
]);
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment