Hello I am hoping someone can provide me feedback on my solution to this prob. If there are additional edge cases I should consider etc. Thank you!
The question: "Given a sentence with a set of delimiters, reverse the order of the words in the sentence and keep the delimiters in place."
let isAlpha = (char) => {
let pat = /[a-zA-z]/igm; // match any alphabetic character
if(char.match(pat)){
return true
} else {
return false
}
}
function reverse(s){
let specialArr = []
for(ltr of s){
if(!isAlpha(ltr)){ // pull out all special characters in order
specialArr.push(ltr)
}
}
let regCharArr = s.split(/[^a-z]/ig).reverse() // use split to pull out all words separated by non alpha characters. then reverse
let result = [] // init result array
if(isAlpha(s[0])){
result = regCharArr.flatMap((val, idx) => [val, specialArr[idx]]) //use flatmap to combine the two arrays...if origin array starts with letter, combine special array into reg array
}
if(!isAlpha(s[0])){
result = specialArr.flatMap((val, idx) => [val, regCharArr[idx]]) // vice versa
}
for(let i = 0; i < result.length; i++){ // remove any undefineds
if(result[i] === undefined){
result.splice(i, 1)
}
}
return result.join('')
}
// let sentence = "one|twotwo/three:four" // four|three/twotwo:one
let sentence = "|brian/steve:chris|jon" // |jon/chris:steve|brian
console.log(reverse(sentence))
```
"#a!!b?c"
? \$\endgroup\$