Last active
March 11, 2019 11:11
-
-
Save piecioshka/6021777 to your computer and use it in GitHub Desktop.
[periodic time]
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
function getPeriod(period) { | |
var number, letter, letters, time; | |
if (typeof period !== "string") { | |
throw new Error("sorry, only string is correct, not " + typeof period); | |
} | |
/** | |
* Parse number from period. | |
* @type {number} | |
*/ | |
number = parseInt(period, 10); | |
/** | |
* Parse letters from period. | |
* @type {Array} | |
*/ | |
letters = period.match(/[a-z]/mig); | |
if (letters === null) { | |
throw new Error("give me some letters in \"" + period + "\""); | |
} | |
/** | |
* Cast *Array* to lower case *string*. | |
* @type {string} | |
*/ | |
letter = letters.join("").toLowerCase(); | |
/** | |
* Start build time from number. | |
* @type {number} | |
*/ | |
time = number; | |
/** | |
* Transform time to concrete period. | |
*/ | |
switch (letter) { | |
case "ms": break; | |
case "s": time *= 1000; break; | |
case "m": time *= 1000 * 60; break; | |
case "h": time *= 1000 * 60 * 60; break; | |
case "d": time *= 1000 * 60 * 60 * 24; break; | |
case "o": time *= 1000 * 60 * 60 * 24 * 30; break; // month is 30 days | |
case "y": time *= 1000 * 60 * 60 * 24 * 365; break; // year is 365 days | |
} | |
return time; | |
}; | |
/** | |
* TEST DATA | |
*/ | |
["10ms", "3s", "5m", "1h", "7d", "1o", "3y"].forEach(function (period) { | |
console.log(getPeriod(period)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment