Created
October 4, 2019 13:13
-
-
Save mikemaccana/d9372cbd1acddbd4ff1ac1d015882168 to your computer and use it in GitHub Desktop.
Number methods (5..days etc) in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Stolen from https://github.com/mikemaccana/agave/blob/master/index.js | |
const MILLISECONDS_IN_SECOND = 1000, | |
SECONDS_IN_MINUTE = 60, | |
MINUTES_IN_HOUR = 60, | |
HOURS_IN_DAY = 24, | |
DAYS_IN_WEEK = 7, | |
DAYS_IN_MONTH = 30, | |
DAYS_IN_YEAR = 365 | |
// Normally you'd name functions with a verb, but since | |
// these are properties of Number, it's OK | |
var seconds = function () { | |
return this * MILLISECONDS_IN_SECOND | |
} | |
var minutes = function () { | |
return this.seconds * SECONDS_IN_MINUTE | |
} | |
var hours = function () { | |
return this.minutes * MINUTES_IN_HOUR | |
} | |
var days = function () { | |
return this.hours * HOURS_IN_DAY | |
} | |
var weeks = function () { | |
return this.days * DAYS_IN_WEEK | |
} | |
var years = function () { | |
return this.days * DAYS_IN_YEAR | |
} | |
var newAttributes = { | |
Number: { | |
seconds, | |
minutes, | |
hours, | |
days, | |
weeks, | |
years, | |
// And the singular properties | |
second: seconds, | |
minute: minutes, | |
hour: hours, | |
day: days, | |
week: weeks, | |
year: years | |
} | |
} | |
// Add sttribute as a non-enumerable property on obj with the name methodName | |
var addNewAttribute = function (objectName, methodName, method) { | |
var objectToExtend = global[objectName] | |
// Don't add if the method already exists | |
if (!objectToExtend.prototype.hasOwnProperty(methodName)) { | |
Object.defineProperty(objectToExtend.prototype, methodName, { | |
get: method | |
}) | |
} | |
} | |
for (var objectToGetNewAttribute in newAttributes) { | |
for (var attributeName in newAttributes[objectToGetNewAttribute]) { | |
addNewAttribute(objectToGetNewAttribute, attributeName, newAttributes[objectToGetNewAttribute][attributeName]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment