String.prototype.indexesOf()

Would work like

String.prototype.indexesOf = function(char) {
    return [...this.matchAll(new RegExp(char, 'gi'))].map(a => a.index) // Returns array of indexes
}

It's easy enough to do yourself. Would like to see this added.

That particularly implementation would fail on any char that required escaping in a regex. What you want is something a bit different.

Either way tho, what's the use case? Why would you need all the matching indexes?

1 Like

e.g. remove all of character x of a string would be like

let str = 'banana'

// remove every n
let ns = string.indexesOf('n');
for (var i = 0; i < ns.length; i++) {
    str = str.substring(0, ns[i] - 1) + str.substring(ns[i], str.length);
}

console.log(str); // <-- baaa

or str.replaceAll('n', '')?

1 Like

You could iterate through all indices using

for (var i = -1; (i = string.indexOf('n', i + 1)) !== -1;) {
   // ...
}
1 Like

I would really like a generic-type implementation named keysOf, that returns all keys of an Object, Map, or Array that match an arbitrary predicate:

const isEven = x => typeof x == 'bigint' ?
    (x & 1n) == 0n :
    Number.isInteger(x) && x % 2 == 0;

const arr = [0, 1n, 2n, 3, 'hello'];
keysOf(arr, isEven); //['0', '2']

const map = new Map();
arr.forEach(x => map.set(x, x));
keysOf(map, isEven); //[0, 2n]

This seems easy enough today with keys() + filter(). For arrays, maps, and sets iterator helpers smooths this out a bit since their keys() methods return iterators and not arrays (like you'd get with Object.keys()).

2 Likes

I agree with that. Iterator helpers are a good idea for this, since generators can be potentially infinite, also because lazy evaluation is good for speed and memory use