Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
- Start with first character:
'+' - Compare with next:
'+' === '+'? result'+' - Continue:
'+' === '+'? result'+' - Next:
'+' !== '-'? result'-' - 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.
