From 64e813263aa5bf1f223b102ecae302da2db106b7 Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Fri, 3 May 2024 10:43:01 +0200 Subject: [PATCH] :bug: - Fix binding of Array.get, to make sure it boxes options --- src/Core__Array.mjs | 10 +++++++++- src/Core__Array.res | 8 +++++++- src/Core__Array.resi | 3 +-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/Core__Array.mjs b/src/Core__Array.mjs index f33b3840..1fcad11b 100644 --- a/src/Core__Array.mjs +++ b/src/Core__Array.mjs @@ -99,6 +99,13 @@ function reduceRightWithIndex(arr, init, f) { return arr.reduceRight(f, init); } +function get(arr, i) { + if (i >= 0 && i < arr.length) { + return Caml_option.some(arr[i]); + } + +} + function findIndexOpt(array, finder) { var index = array.findIndex(finder); if (index !== -1) { @@ -166,7 +173,7 @@ function findMap(arr, f) { } function last(a) { - return a[a.length - 1 | 0]; + return get(a, a.length - 1 | 0); } export { @@ -180,6 +187,7 @@ export { reduceWithIndex , reduceRight , reduceRightWithIndex , + get , findIndexOpt , filterMap , keepSome , diff --git a/src/Core__Array.res b/src/Core__Array.res index a80a8e10..784d3f6b 100644 --- a/src/Core__Array.res +++ b/src/Core__Array.res @@ -184,7 +184,13 @@ let reduceRightWithIndex = (arr, init, f) => reduceRightWithIndex(arr, f, init) @send external some: (array<'a>, 'a => bool) => bool = "some" @send external someWithIndex: (array<'a>, ('a, int) => bool) => bool = "some" -@get_index external get: (array<'a>, int) => option<'a> = "" +let get = (arr, i) => + if i >= 0 && i < length(arr) { + Some(getUnsafe(arr, i)) + } else { + None + } + @set_index external set: (array<'a>, int, 'a) => unit = "" @get_index external getSymbol: (array<'a>, Core__Symbol.t) => option<'b> = "" diff --git a/src/Core__Array.resi b/src/Core__Array.resi index 529aa9cd..9746e86b 100644 --- a/src/Core__Array.resi +++ b/src/Core__Array.resi @@ -822,8 +822,7 @@ array->Array.get(0) == Some("Hello") // true array->Array.get(3) == None // true ``` */ -@get_index -external get: (array<'a>, int) => option<'a> = "" +let get: (array<'a>, int) => option<'a> /** `set(array, index, item)` sets the provided `item` at `index` of `array`.