Skip to content

Add more methods to the array helper #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/core/lib/utils/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,48 @@ export class Arr {

return undefined;
}

static exists<T = any>(arr: T[], key: string | number): boolean {
if (typeof key === 'number' && key >= 0 && key < arr.length) {
return true;
}

if (typeof key === 'string') {
const splitKeys = key.split('.');
if (!splitKeys.length) return false;

if (Arr.isArray(arr[splitKeys[0]])) {
return Arr.exists(arr[splitKeys[0]], splitKeys.slice(1).join('.'));
}

if (Obj.isObj(arr[splitKeys[0]])) {
return (
Obj.get(arr[splitKeys[0]], splitKeys.slice(1).join('.')) !== undefined
);
}
}

return false;
}

static last<T = any>(
arr: T[],
predicate?: ((item: T, index: number, array: T[]) => boolean) | null,
): T | undefined {
if (!arr || arr.length === 0) {
return undefined;
}

if (!predicate) {
return arr[arr.length - 1];
}

for (let i = arr.length - 1; i >= 0; i--) {
if (predicate(arr[i], i, arr)) {
return arr[i];
}
}

return undefined;
}
}
36 changes: 36 additions & 0 deletions packages/core/tests/helpers/arrayHelper.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Arr } from '../../lib/utils/array';

describe('Array Helper', () => {
beforeEach(async () => {});

it('check key exists', () => {
const arr = [1, 2, 3, 4, 5];
expect(Arr.exists(arr, 2)).toBeTruthy();
});

it('check key does not exist', () => {
const arr = [1, 2, 3, 4, 5];
expect(Arr.exists(arr, 6)).toBeFalsy();
});

it('should return last element matching predicate', () => {
const arr = [1, 2, 3, 4, 5];
expect(Arr.last(arr, x => x < 4)).toBe(3);
expect(Arr.last(arr)).toBe(5);
});

it('should return the last object that matches the predicate', () => {
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
{ name: 'David', age: 30 },
];
const lastUserUnder35 = Arr.last(users, user => user.age < 35);
expect(lastUserUnder35).toEqual({ name: 'David', age: 30 });
});

it('should return undefined for empty array', () => {
expect(Arr.last([])).toBeUndefined();
});
});