patternjavascriptMinor
String manipulations: transform "a-b-c" into "a(b(c))"
Viewed 0 times
transformintostringmanipulations
Problem
function dashesToParentheses(str) {
var list = str.split('-');
return str.replace(/-/g, '(') + repeatString(')', list.length - 1);
}
function repeatString(str, times) {
if (times == 1)
return str;
return new Array(times + 1).join(str);
}
dashesToParentheses('a-b-c') // "a(b(c))"
dashesToParentheses('a-b') // "a(b)"
dashesToParentheses('a') // "a"
dashesToParentheses('') // ""dashesToParentheses works correct. Can I make it simpler or/and faster?
Solution
Having split the string you can join it with brackets instead of replacing them. You could optionally choose to remove the repeatString function and your +/- 1, but it does make a lot of sense the way you have it.
function dashesToParentheses(str) {
var list = str.split('-');
return list.join('(') + Array(list.length).join(')');
}Code Snippets
function dashesToParentheses(str) {
var list = str.split('-');
return list.join('(') + Array(list.length).join(')');
}Context
StackExchange Code Review Q#6790, answer score: 8
Revisions (0)
No revisions yet.