Created
March 9, 2017 13:14
-
-
Save zacck-zz/dc8abde6412307ab8f865a355e252b9d 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
| // 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