Skip to content

Instantly share code, notes, and snippets.

@zacck-zz
Created March 9, 2017 13:14
Show Gist options
  • Select an option

  • Save zacck-zz/dc8abde6412307ab8f865a355e252b9d to your computer and use it in GitHub Desktop.

Select an option

Save zacck-zz/dc8abde6412307ab8f865a355e252b9d to your computer and use it in GitHub Desktop.
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(S) {
// write your code in JavaScript (Node.js 6.4.0)
var numericString = S.trim;
var finalString = '';
//lets remove all the non numeric characters in the string
numericString = S.replace(/\s|-/g, '');
//we removed the chuff ensure we have more than 2 characters
//watch our edge cases
//this can be made skinnier and more perfomant
while(numericString.length > 0) {
if(numericString.length <= 2) {
finalString += `${numericString.substr(0,2)}`;
break;
}
if(numericString.length <= 3) {
finalString += `${numericString.substr(0,3)}`;
break;
}
if(numericString.length == 4) {
finalString += `${numericString.substr(0,2)}-`;
numericString = numericString.replace(/^.{0,2}/, '');
finalString += `${numericString.substr(0,2)}`
break;
}
finalString += `${numericString.substr(0,3)}-`;
numericString = numericString.replace(/^.{0,3}/, '');
}
return finalString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment