Skip to content

Commit

Permalink
Enhance arrays with a remove by predicate function.
Browse files Browse the repository at this point in the history
the new function behaves similar to the existing remove function but
takes a predicate to find the first matching array element to remove.
This way the caller is given more control on the equals check.
  • Loading branch information
cyrill-wyss authored and cguglielmo committed Jul 27, 2023
1 parent f312529 commit 9826678
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions eclipse-scout-core/src/util/arrays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,10 @@ export const arrays = {
},

/**
* Removes the first occurrence of the specified element from the array,
* if it is present (optional operation). If the array does not contain
* the element, it is unchanged.
* Removes the first occurrence of the specified element from the array.
* If the array does not contain the element, it stays unchanged.
*
* @returns true if the array contained the specified element
* @returns true if an element was removed
*/
remove<T>(arr: T[], element: T): boolean {
if (arr) {
Expand All @@ -52,6 +51,21 @@ export const arrays = {
return false;
},

/**
* Removes the first array element that matches the given predicate.
* If no element matches the given predicate, the array stays unchanged.
*
* @returns true if an element was removed
*/
removeByPredicate<T>(arr: T[], predicate: (elem: T, index: number, arr: T[]) => boolean, thisArg?: any): boolean {
let index = arrays.findIndex(arr, predicate, thisArg);
if (index !== -1) {
arr.splice(index, 1);
return true;
}
return false;
},

/**
* Removes every given element from the array
*
Expand Down

0 comments on commit 9826678

Please sign in to comment.