7
\$\begingroup\$
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?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 13, 2011 at 10:16
\$\endgroup\$

3 Answers 3

8
\$\begingroup\$

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(')');
}
answered Dec 13, 2011 at 11:35
\$\endgroup\$
2
\$\begingroup\$

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 + ')';
 }, '');
};
answered Dec 13, 2011 at 11:29
\$\endgroup\$
1
\$\begingroup\$

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, ")");
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered May 10, 2015 at 20:17
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.