Created
May 26, 2020 18:33
-
-
Save thiagozs/45b8fac6ad13b787eb4b9da1b6a4a17d to your computer and use it in GitHub Desktop.
Challenge QuintoAndar
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
package main | |
import ( | |
"fmt" | |
"regexp" | |
) | |
const SEPARATOR = "-" | |
func main() { | |
case1 := "00-44 48 5555 8361" | |
case2 := "0 - 22 1985--324" | |
case3 := "555372654" | |
fmt.Println("case1: ", parse(case1)) //case1: 004-448-555-583-61 | |
fmt.Println("case2: ", parse(case2)) //case2: 022-198-53-24 | |
fmt.Println("case3: ", parse(case3)) //case3: 555-372-654 | |
} | |
func parse(input string) string { | |
reg, err := regexp.Compile("[^0-9]+") | |
if err != nil { | |
panic(err) | |
} | |
input = reg.ReplaceAllString(input, "") | |
inputLength := len(input) | |
if inputLength <= 3 { | |
return input | |
} else { | |
mod := inputLength % 3 | |
if mod == 0 { | |
return split3(input) | |
} else if mod == 1 { | |
baseEnd := inputLength - 4 | |
base := split3(input[0:baseEnd]) | |
suffix := split2(input[baseEnd:inputLength]) | |
return base + "-" + suffix | |
} else { | |
baseEnd := inputLength - 2 | |
base := split3(input[0:baseEnd]) | |
suffix := input[baseEnd:inputLength] | |
return base + "-" + suffix | |
} | |
} | |
} | |
func split2(input string) string { | |
return splitTemplate(input, 2) | |
} | |
func split3(input string) string { | |
return splitTemplate(input, 3) | |
} | |
func splitTemplate(input string, splitSize int) string { | |
result := "" | |
for i := 0; i < len(input); i += splitSize { | |
sub := input[i : i+splitSize] | |
result += sub | |
if i != (len(input) - splitSize) { | |
result += SEPARATOR | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment