jeudi 2 mai 2019

Weird behaviour when returning char.pop() inside if statement

Problem

I've created (or tried to create) a JS function that reverses a string ignoring special characters. The function doesn't work when there are 2 consecutive special characters.

Code

I provide all the code necessary to reproduce the problem bellow. including some tests that you can run with mocha. The second test fails.

The following code passes the tests:

const assert = require('assert');

const reverseButNoSpecial = (str) => {
    const specialChars = /[^a-zA-Z ]/g;

    // create an array withOUT special chars
    const cleanArray = str.replace(specialChars, "").split('');

    // iterate over the original
    // replace each letter with a letter from the clean array,
    // leave the special chars
    return str.split('').map(char => {
        if (specialChars.test(char)) {
            return char;
        }
        // remove the last char from the reversed array
        const removed = cleanArray.pop();
        // return the char that was removed
        return removed;
    }).join('');
}

describe('Reverse all characters except special chars', () => {
    it ('should work for a,b$c!', () => {
        expected = 'c,b$a!';
        actual = reverseButNoSpecial('a,b$c!');
        assert.strictEqual(expected, actual);
    })

    it ('should work for Ab,c,d$$e!', () => {
        expected = 'ed,c,b$$A!';
        actual = reverseButNoSpecial('Ab,c,d$$e!');
        assert.strictEqual(expected, actual);
    })
})

Expected vs Actual

Expected reverseButNoSpecial('Ab,c,d$$e!') to return ed,c,b$$A! but got ed,c,b$A!

(notice the $ appears only once when it should appear twice $$

Can someone help me figure out why?

Aucun commentaire:

Enregistrer un commentaire