I have these strings:
)hello(
this has ]some text[
flip }any{ brackets
even with )))]multiple[((( brackets
As you can see, the brackets are all in the wrong direction.
I have a function called flipBracketsDirection() to handle each scenario. Here is an example of input and output of the above strings:
flipBracketsDirection(')hello(');
// should return: (hello)
flipBracketsDirection('this has ]some text[');
// should return: this has [some text]
flipBracketsDirection('flip }any{ brackets');
// should return: flip {any} brackets
flipBracketsDirection('even with )))]multiple[((( brackets');
// should return: even with ((([multiple]))) brackets
Note: The direction is flipped at all times. So this is fine too:
flipBracketsDirection('flip (it) anyway');
// should return: flip )it( anyway
Here is my solution.
function flipBracketsDirection(str: string) {
return str
// flip () brackets
.replace(/\(/g, 'tempBracket').replace(/\)/g, '(').replace(/tempBracket/g, ')')
// flip [] brackets
.replace(/\[/g, 'tempBracket').replace(/\]/g, '[').replace(/tempBracket/g, ']')
// flip {} brackets
.replace(/\{/g, 'tempBracket').replace(/\}/g, '{').replace(/tempBracket/g, '}')
;
}
Is this the best way to create this function?