2
\$\begingroup\$

I wanted to write a function to remove a set of characters from a string in JavaScript.

I came up with this.

How can it be improved in terms of time/space complexity?

function remove(str, chars) {
    var set = new Set(chars); // looking up presence of char is O(1)
    var arr = [...str]; // operate on an arrray rather than a string to avoid unneccessary string copying
    // What follows is O(N) I think...
    return arr.reduce((p,c) => {
        if(set.has(c)) {
            return p;
        }
        p.push(c);
        return p;
    }, []).join('');
}

remove('hello world', 'el') === 'ho word';

\$\endgroup\$
2
  • \$\begingroup\$ Why not use regex? \$\endgroup\$
    – yuri
    Commented Jun 6, 2017 at 9:13
  • \$\begingroup\$ A good option... \$\endgroup\$
    – 52d6c6af
    Commented Jun 6, 2017 at 9:23

1 Answer 1

4
\$\begingroup\$
  • Don't abuse reduce. Reduce should be used when you want to reduce the list. Take using reduce to find the sum of a list: [1, 2, 3].reduce((a, b) => a + b, 0).
  • Use filter if you want to filter a list. arr.filter(i => !set.has(i)).
  • You may want to instead use regex.replace. However, it'd require checking your chars for any regex escape stuff.

    However if you ignore that, it could be as easy as:

    function remove(str, chars) {
      return str.replace(new RegExp(`[${chars}]`, 'g'), '');
    }
    

Otherwise using the above, for \$O(n)\$ time and space complexity, could get you:

function remove(str, chars) {
    var set = new Set(chars);
    return [...str].filter(i => !set.has(i)).join('');
}
\$\endgroup\$
2
  • \$\begingroup\$ By the verb reduce you mean perform an aggregation function on the collection? \$\endgroup\$
    – 52d6c6af
    Commented Jun 6, 2017 at 9:41
  • 1
    \$\begingroup\$ @Ben Yes that, :) As you should reduce from a List<T> to a T. \$\endgroup\$
    – Peilonrayz
    Commented Jun 6, 2017 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.