Last active
August 29, 2015 14:00
-
-
Save hoodwink73/11083077 to your computer and use it in GitHub Desktop.
A general method which splits a metric expressed in a single smaller unit into multiple higher units
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
// A general method which splits a metric | |
// expressed in a single smaller unit into multiple | |
// higher units | |
// 1689 minutes => 1 day 9 hours 9 minutes | |
// 1678 millimeter => 1 meter 67 centimeter 8 millimeter | |
// The method takes two parameters, the metric itself | |
// and an array which defines the conversion | |
// Say, you want to convert x minutes to | |
// a days b hours and c minutes | |
// the conversion array would take in | |
// [1140, 60, 1] | |
// 1 day = 1440 minutes | |
// 1 hour = 60 minutes | |
// 1 minute = 1 minute | |
// Note: Array.shift() returns the first element of the | |
// array and removes it in place | |
// arr = [1, 2] | |
// arr.shift() => 1 | |
// arr => [2] | |
function formatUnit (metric, divisions) { | |
var result = []; | |
// a recursive function which repeatedly breaks | |
// the metric into higher units until it can be | |
// be expressed in the unit in which it was passed as | |
function smasher(reducedMetric, division) { | |
// if we have exhausted all the conversion rule | |
// pass the result | |
if (!divisions.length) { | |
result.push(reducedMetric); | |
return result; | |
} else { | |
// if the current metric is less than | |
// one unit of the current unit | |
// (like 30 minutes < 1 hour) | |
if (reducedMetric < division) { | |
result.push(0); | |
return smasher(reducedMetric, divisions.shift()); | |
} else { | |
result.push(Math.floor(reducedMetric / division)); | |
return smasher(reducedMetric % division, divisions.shift()); | |
} | |
} | |
} | |
return smasher(metric, divisions.shift()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment