Toptal | OA | Format Number
1046

Format given number into blocks of 3
for eg: XXX-XXX
Last one or two blocks can be of 2 digits
These are allowed: XXX-XXX-XX or XXX-XX-XX

Test Cases

[
   	{
   		input: '00-44 48 5555 8361',
   		output: '004-448-555-583-61',
   	},
   	{
   		input: '0 - 22 1985--324',
   		output: '022-198-53-24',
   	},
   	{
   		input: '555372654',
   		output: '555-372-654',
   	},
   ]

Solution

function formatNumber(S) {
   const length = S.length

   // store all numbers
   let finalCharacters = []
   for (let i = 0; i < length; i++) {
   	const code = S.charCodeAt(i)
   	if (code >= 48 && code <= 57) {
   		finalCharacters.push(S[i])
   	}
   }

   const numOfChar = finalCharacters.length

   // number of blocks of two in the end
   // depends on numOfChar % 3
   let blocksOfTwo
   if (numOfChar % 3 === 0) blocksOfTwo = 0
   else if (numOfChar % 3 === 1) blocksOfTwo = 2
   else if (numOfChar % 3 === 2) blocksOfTwo = 1

   let result = ''

   // maitain count of numbers already added to a block
   let blockCount = 0

   while (finalCharacters.length) {
   	if (blockCount === 2 && blocksOfTwo) {
   		// reset count of numbers in block
   		blockCount = 0

   		// reduce how many blocks of two are needed
   		blocksOfTwo--
   		result = '-' + result
   	} else if (blockCount === 3) {
   		// reset count of numbers in block
   		blockCount = 0
   		result = '-' + result
   	} else {
   		result = finalCharacters.pop() + result

   		// increment count of numbers in block
   		blockCount++
   	}
   }
   return result
}
Comments (2)