Array.prototype.remove(item)

Man Hoang jolleekin at outlook.com
Wed Oct 10 02:10:48 UTC 2018


There are cases that you only want to remove the first occurrence of an item (because you know there is at most one occurrence of that item) and there are cases that you want to remove more than one item. Therefore, I propose adding the following methods (written in TypeScript here for static typing support), optimizing for each use case.

class Array<E> {
    /**
     * Removes the first occurrence of [item] from this array.
     *
     * Returns `true` if [item] was in this array and `false` otherwise.
     */
    remove(item: E): boolean {
        const i = this.indexOf(item);
        if (i >= 0) {
            this.splice(i, 1);
            return true;
        }
        return false;
    }

    /**
     * Removes all items that satisfies the predicate [test].
     * @returns The number of removed items.
     */
    removeWhere(test: (item: E) => boolean): number {
        let count = 0;
        for (let i = this.length - 1; i >= 0; i--) {
            if (test(this[i])) {
                this.splice(i, 1);
                count++;
            }
        }
        return count;
    }
}

References

  *   [C#] List.Remove<https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove?view=netframework-4.7.2>
  *   [C#] List.RemoveAll<https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=netframework-4.7.2>
  *   [Dart] List.remove<https://api.dartlang.org/stable/2.0.0/dart-core/List/remove.html>
  *   [Dart] List.removeWhere<https://api.dartlang.org/stable/2.0.0/dart-core/List/removeWhere.html>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20181010/23797cb5/attachment-0001.html>


More information about the es-discuss mailing list