Skip to content
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@phanect/utils",
"version": "2.0.0",
"version": "2.0.1",
"description": "@phanect's personal utility library for JavaScript & TypeScript",
"repository": {
"type": "git",
Expand Down
14 changes: 5 additions & 9 deletions src/universal/get-last-element-of.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function getLastElementOf<T>(
options: {
withIndex?: boolean;
} = {},
): T | { el: T; index: number; } | undefined {
): T | { el: T | undefined; index: number; } | undefined {
Comment thread
phanect marked this conversation as resolved.
if (arr.length <= 0) {
return undefined;
}
Expand All @@ -29,14 +29,10 @@ export function getLastElementOf<T>(
if (withIndex === true) {
const index = arr.length - 1;

if (arr[index]) {
return {
el: arr[index],
index,
};
} else {
return undefined;
}
return {
el: arr[index],
index,
};
Comment thread
phanect marked this conversation as resolved.
} else {
return arr[arr.length - 1];
}
Expand Down
27 changes: 27 additions & 0 deletions test/universal/get-last-element-of.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,30 @@ test("getLastElementOf (with index, empty array given)", () => {

expect(lastElement).toBeUndefined();
});

test("undefined element (without index)", () => {
const lastElement = getLastElementOf([ "a", "b", undefined, "c", undefined ], { withIndex: false });

expect(lastElement).toBeUndefined();
});

test("undefined element (with index)", () => {
const { el, index } = getLastElementOf([ "a", "b", undefined, "c", undefined ], { withIndex: true }) ?? {};

expect(el).toBeUndefined();
expect(index).toBe(4);
});

test("false element (with index)", () => {
const { el, index } = getLastElementOf([ "a", "b", false ], { withIndex: true }) ?? {};

expect(el).toBe(false);
expect(index).toBe(2);
});

test("empty string element (with index)", () => {
const { el, index } = getLastElementOf([ "a", "b", "" ], { withIndex: true }) ?? {};

expect(el).toBe("");
expect(index).toBe(2);
});