Neutralisation of strings - JavaScript

In JavaScript, string neutralisation involves evaluating a string containing only '+' and '-' characters to determine the overall sign. The concept is based on mathematical sign multiplication: like signs produce '+', unlike signs produce '-'.

How Neutralisation Works

The neutralisation follows these rules:

  • ++ results in + (positive × positive = positive)
  • -- results in + (negative × negative = positive)
  • +- or -+ results in - (positive × negative = negative)

Example String

Let's work with the following string:

const str = '+++-+-++---+-+--+-';

Implementation

Here's how to implement string neutralisation using the reduce method:

const str = '+++-+-++---+-+--+-';

const netResult = (str = '') => {
    const strArr = str.split('');
    return strArr.reduce((acc, val) => {
        if (acc === val) {
            return '+';
        }
        return '-';
    });
};

console.log(netResult(str));
-

Alternative Approach Using Character Counting

Another method is to count negative signs. If the count is even, result is '+'; if odd, result is '-':

const str = '+++-+-++---+-+--+-';

const netResultByCount = (str = '') => {
    let negativeCount = 0;
    for (let char of str) {
        if (char === '-') {
            negativeCount++;
        }
    }
    return negativeCount % 2 === 0 ? '+' : '-';
};

console.log(netResultByCount(str));
-

Step-by-Step Process

For the string '+++-+-++---+-+--+-', the neutralisation works as follows:

  1. Start with first character: '+'
  2. Compare with next: '+' === '+' ? result '+'
  3. Continue: '+' === '+' ? result '+'
  4. Next: '+' !== '-' ? result '-'
  5. Continue this process through all characters

Comparison of Methods

Method Time Complexity Readability
Reduce Method O(n) Functional approach
Count Method O(n) More intuitive

Conclusion

String neutralisation in JavaScript can be achieved through sequential comparison or by counting negative signs. Both methods effectively determine the overall sign based on mathematical neutralisation rules.

Updated on: 2026-03-15T23:18:59+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements