Skip to content

Instantly share code, notes, and snippets.

@Kadrian
Created November 10, 2016 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kadrian/2d74d04ab7a01a7c26adff1abd247f61 to your computer and use it in GitHub Desktop.
Save Kadrian/2d74d04ab7a01a7c26adff1abd247f61 to your computer and use it in GitHub Desktop.
// Trying to find the best solution to the following problem:
//
// Display a large number with a small space in between steps of thousand.
// Thus => Convert a number to an array of max. three digits
//
// E.g.
// Input: 10 Output: [10]
// Input: 1234 Output: [1, 234]
// Input: 24521280 Output: [23, 521, 280]
// Here are my attempts (all working solutions)
// The first "make it work without thinking much"-version
const numberToThreeDigitArray = (number) => {
const numberStr = number.toString();
let threeDigitSequences = [];
let threeDigits = [];
for (let i = numberStr.length - 1; i >= 0; i--) {
threeDigits = [numberStr[i]].concat(threeDigits);
if ((numberStr.length - i) % 3 === 0) {
threeDigitSequences = [threeDigits.join('')].concat(threeDigitSequences)
threeDigits = [];
}
// Final push
if (i === 0 && threeDigits.length > 0)
threeDigitSequences = [threeDigits.join('')].concat(threeDigitSequences)
}
return threeDigitSequences;
};
// The "think a little before doing"-version
const numberToThreeDigitArray = (number) => {
if (number / 1000 < 1) return [number];
return [
...numberToThreeDigitArray(Math.floor(number / 1000)),
number % 1000
];
};
// The third "why don't we do string iteration"-version
const numberToThreeDigitArray = (number) => {
return number.toString().split('').reverse().map((char, i) => {
return i !== 0 && i % 3 === 0
? ' ' + char
: char;
}).join('').split('').reverse().join('').split(' ');
}
// => Not really happy with either solution yet, but so far I prefer solution 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment