Skip to content

Instantly share code, notes, and snippets.

@reyronald
Last active November 3, 2023 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyronald/e7aa3115b5f6f9f6aa8668fbb14106a7 to your computer and use it in GitHub Desktop.
Save reyronald/e7aa3115b5f6f9f6aa8668fbb14106a7 to your computer and use it in GitHub Desktop.

FindAndPopCollection

Usage:

const array = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

const collection = new FindAndRemoveCollection(array)

collection.findAndRemove(item => item === 'Tuesday') // Returns 'Tuesday'
// collection now has ['Monday', 'Wednesday', 'Thursday', 'Friday']

collection.findAndRemove(item => item === 'Tuesday') // Returns undefined

If you don't want to create a new class, you can always use it inline or anonymously:

const array = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

const collection = new (class FindAndPopCollection<T> {
  private _array: T[];

  constructor(_array: T[]) {
    this._array = _array.slice();
  }

  findAndRemove(predicate: (value: T) => boolean) {
    const index = this._array.findIndex(predicate);
    if (index !== -1) {
      const value = this._array[index];
      this._array.splice(index, 1);
      return value;
    }
  }
})(array);
class FindAndPopCollection<T> {
private _array: T[];
constructor(_array: T[]) {
this._array = _array.slice();
}
findAndRemove(predicate: (value: T) => boolean) {
const index = this._array.findIndex(predicate);
if (index !== -1) {
const value = this._array[index];
this._array.splice(index, 1);
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment