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?
3 Answers 3
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(')');
}
Well, you could remove the RegExp. But whether that helps performance is anyone's guess.
var d2p = function(s){
var one=[], two=[], a=s.split('-');
one.push(a.shift());
a.forEach(function(part){
one.push('(' + part);
two.push(')');
});
return one.join('') + two.join('');
};
If you don't mind having the result fully parenthesised, then you can do this:
var d2p = function(s){
return s.split('-').reduceRight(function(whole, part){
return '(' + part + whole + ')';
}, '');
};
The first term is obvious: Just replace all dashes by opening parentheses. The second replaces all dashes by closing parentheses while dropping everything else.
function dashesToParentheses(str) {
return str.replace(/-/g, "(") + str.replace(/[^-]*-[^-]*/g, ")");
}