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?

\$\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(')');
}
\$\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 + ')';
    }, '');
};
\$\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, ")");
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.