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';