Skip to content

Instantly share code, notes, and snippets.

@googlicius
Last active June 1, 2018 06:50
Show Gist options
  • Save googlicius/0913eb2087bfa7b8b83562ec6baec5d0 to your computer and use it in GitHub Desktop.
Save googlicius/0913eb2087bfa7b8b83562ec6baec5d0 to your computer and use it in GitHub Desktop.
Declarative ways to get time in months|days|hours|seconds|miliseconds later (or of) months|days|minutes|seconds
/**
* Get time in months|days|hours|seconds|miliseconds later (or of) months|days|hours|seconds|miliseconds
*
* Examples:
* timeIn('second').later(30).minutes();
* timeIn('second').of(2).days();
*
* @param {string} name
* @return {object} { later, of }
*/
exports.timeIn = (name = 'milisecond') => {
const output = (timeInMs) => {
const milisecondTo = {
month() {
return timeInMs / 1000 / 60 / 60 / 24 / 30;
},
day() {
return timeInMs / 1000 / 60 / 60 / 24;
},
hour() {
return timeInMs / 1000 / 60 / 60;
},
minute() {
return timeInMs / 1000 / 60;
},
second() {
return timeInMs / 1000;
},
milisecond() {
return timeInMs;
}
}
name = name.replace(/s+$/, '');
try {
return milisecondTo[name]();
} catch (error) {
throw new Error(name + " is not a function");
}
}
const timeMaker = (number, from = Date.now()) => {
if(typeof number != 'number') {
throw new Error("number must be in number type");
}
const milisecondBy = {
month() {
return from + (number * 1000 * 60 * 60 * 24 * 30)
},
day() {
return from + (number * 1000 * 60 * 60 * 24)
},
hour() {
return from + (number * 1000 * 60 * 60)
},
minute() {
return from + (number * 1000 * 60)
},
second() {
return from + (number * 1000)
},
milisecond() {
return from + number
},
}
const toOutput = (name) => {
name = name.replace(/s+$/, '');
try {
const timeInMs = milisecondBy[name]();
return output(timeInMs);
} catch (error) {
throw new Error(name + " is not a function");
}
}
return {
month: () => toOutput('month'),
months: () => toOutput('month'),
day: () => toOutput('day'),
days: () => toOutput('day'),
hour: () => toOutput('hour'),
hours: () => toOutput('hour'),
minute: () => toOutput('minute'),
minutes: () => toOutput('minute'),
second: () => toOutput('second'),
seconds: () => toOutput('second'),
milisecond: () => toOutput('milisecond'),
miliseconds: () => toOutput('milisecond'),
}
}
const later = number => timeMaker(number);
const of = number => timeMaker(number, 0);
return { later, of }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment