Removing parentheses from mathematical expressions in JavaScript

JavascriptWeb DevelopmentFront End Technology

<h2>Problem</h2><p>We are required to write a JavaScript function that takes in a string of mathematical expressions, str, as the first and the only argument.</p><p>The task of our function is to remove parentheses from the expression keeping the operations and operands in place.</p><p>For example, if the input to the function is &minus;</p><p><strong>Input</strong></p><pre class="prettyprint notranslate">const str = &#39;u-(v-w-(x+y))-z&#39;;</pre><p><strong>Output</strong></p><pre class="result notranslate">const output = &#39;u-v+w+x+y-z&#39;;</pre><h2>Example</h2><p>Following is the code &minus;</p><p><a class="demo" href="http://tpcg.io/1Fln8GWb" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">const str = &#39;u-(v-w-(x+y))-z&#39;; const removeParentheses = (str = &#39;&#39;) =&gt; { &nbsp; &nbsp;let stack = [] &nbsp; &nbsp;let lastSign = &#39;+&#39; &nbsp; &nbsp; &nbsp; for (let char of str) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (char === &#39;(&#39; || char === &#39;)&#39;) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lastSign = stack[stack.length - 1] || &#39;+&#39; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else if (char === &#39;+&#39;) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (stack[stack.length - 1] !== &#39;-&#39; &amp;&amp; stack[stack.length - 1] !== &#39;+&#39;) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;stack.push(lastSign) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else if (char === &#39;-&#39;) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (lastSign === &#39;-&#39;) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (stack[stack.length - 1] === &#39;-&#39;) stack.pop() &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack.push(&#39;+&#39;) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (stack[stack.length - 1] === &#39;+&#39;) stack.pop() &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack.push(&#39;-&#39;) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stack.push(char) &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return stack.join(&#39;&#39;).replace(/^\+/, &#39;&#39;) }; console.log(removeParentheses(str));</pre><h2>Output</h2><pre class="result notranslate">u-v+w+x+y-z</pre>
raja
Updated on 22-Apr-2021 10:28:19

Advertisements