Skip to content

Instantly share code, notes, and snippets.

@dougshamoo
Created February 19, 2016 01:40
Show Gist options
  • Select an option

  • Save dougshamoo/08b0809739470942eac0 to your computer and use it in GitHub Desktop.

Select an option

Save dougshamoo/08b0809739470942eac0 to your computer and use it in GitHub Desktop.
/*
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