Created
February 19, 2016 01:40
-
-
Save dougshamoo/08b0809739470942eac0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 - returns function - shortens long numbers, given array of strings | |
| return function | |
| not numerical string (strings, not a number, arrays) --> number string | |
| INPUT | |
| array of string labels, base number | |
| input to the return function, must be validated | |
| OUTPUT | |
| function that shortens numbers using the labels | |
| CONSTRAINTS | |
| time, space - none | |
| EDGE CASES | |
| no rounding, drop unnecessary digits | |
| filter1 = shortenNumber(['','k','m'],1000); | |
| filter1('234324') == '234k'; | |
| filter1(23456) = '23456'; | |
| filter1('2343245') == '2m'; | |
| filter1('98234324') == '98m'; | |
| 23 / 1 = 23 + '' | |
| */ | |
| //numberShortener, takes arr (labels) and base | |
| // shorten, takes numberString | |
| // validate the input | |
| // if input not a str or not all number chars, return stringified input | |
| // declare num, parse input to number, store in num | |
| // iterate through labels, right to left | |
| // declare scale and init to base to the power of the label index | |
| // declare result and init to num divided by scale, round down | |
| // if greather than or equal to 1 | |
| // return stringified result plus current label | |
| // return shorten | |
| function numberShortener(labels, base) { | |
| return function(numString) { | |
| if (typeof numString !== 'string' || Number.isNaN(parseInt(numString))) { | |
| return String(numString); | |
| } | |
| var num = parseInt(numString); | |
| for (var i = labels.length - 1; i >= 0; i--) { | |
| var scale = Math.pow(base, i); | |
| var result = Math.floor(num / scale); | |
| if (result >= 1) { | |
| return result + labels[i]; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment