Skip to content

Commit

Permalink
Add Array.last
Browse files Browse the repository at this point in the history
  • Loading branch information
DZakh authored and zth committed Dec 30, 2023
1 parent 19183c1 commit 4e73a95
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Core__Array.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ function findMap(arr, f) {
};
}

function last(a) {
return a[a.length - 1 | 0];
}

export {
make ,
fromInitializer ,
Expand All @@ -184,5 +188,6 @@ export {
toShuffled ,
shuffle ,
findMap ,
last ,
}
/* No side effect */
2 changes: 2 additions & 0 deletions src/Core__Array.res
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,5 @@ let findMap = (arr, f) => {
}

@send external at: (array<'a>, int) => option<'a> = "at"

let last = a => a->get(a->length - 1)
15 changes: 15 additions & 0 deletions src/Core__Array.resi
Original file line number Diff line number Diff line change
Expand Up @@ -993,3 +993,18 @@ let findMap: (array<'a>, 'a => option<'b>) => option<'b>
*/
@send
external at: (array<'a>, int) => option<'a> = "at"

/**
`last(array)` returns the last element of `array`.
Returns `None` if the array is empty.
## Examples
```rescript
let array = ["Hello", "Hi", "Good bye"]
array->Array.last == Some("Good bye") // true
[]->Array.last == None // true
```
*/
let last: array<'a> => option<'a>
24 changes: 24 additions & 0 deletions test/ArrayTests.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,30 @@ Test.run([
4
]);

Test.run([
[
"ArrayTests.res",
109,
20,
39
],
"last - with items"
], Core__Array.last([
1,
2,
3
]), eq, 3);

Test.run([
[
"ArrayTests.res",
110,
20,
34
],
"last - empty"
], Core__Array.last([]), eq, undefined);

export {
eq ,
}
Expand Down
3 changes: 3 additions & 0 deletions test/ArrayTests.res
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,6 @@ Test.run(
eq,
[3, 4],
)

Test.run(__POS_OF__("last - with items"), [1, 2, 3]->Array.last, eq, Some(3))
Test.run(__POS_OF__("last - empty"), []->Array.last, eq, None)

0 comments on commit 4e73a95

Please sign in to comment.