diff --git a/src/Core__Array.mjs b/src/Core__Array.mjs index c74602a9..489f569e 100644 --- a/src/Core__Array.mjs +++ b/src/Core__Array.mjs @@ -167,6 +167,10 @@ function findMap(arr, f) { }; } +function last(a) { + return a[a.length - 1 | 0]; +} + export { make , fromInitializer , @@ -184,5 +188,6 @@ export { toShuffled , shuffle , findMap , + last , } /* No side effect */ diff --git a/src/Core__Array.res b/src/Core__Array.res index af04ea3b..db67fbde 100644 --- a/src/Core__Array.res +++ b/src/Core__Array.res @@ -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) diff --git a/src/Core__Array.resi b/src/Core__Array.resi index 15b23f4c..4a49672e 100644 --- a/src/Core__Array.resi +++ b/src/Core__Array.resi @@ -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> diff --git a/test/ArrayTests.mjs b/test/ArrayTests.mjs index 1d1d40e2..b7e9e387 100644 --- a/test/ArrayTests.mjs +++ b/test/ArrayTests.mjs @@ -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 , } diff --git a/test/ArrayTests.res b/test/ArrayTests.res index c18899dd..b6fdec2b 100644 --- a/test/ArrayTests.res +++ b/test/ArrayTests.res @@ -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)