diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ebee649..eb5088e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Next version - Fix: Expose Intl.Common. https://github.com/rescript-association/rescript-core/pull/197 +- Add `Array.flatMapWithIndex` https://github.com/rescript-association/rescript-core/pull/199 ## 1.1.0 diff --git a/src/Core__Array.res b/src/Core__Array.res index 165237b2..a8e6103e 100644 --- a/src/Core__Array.res +++ b/src/Core__Array.res @@ -230,6 +230,7 @@ let filterMap = (a, f) => { let keepSome = filterMap(_, x => x) @send external flatMap: (array<'a>, 'a => array<'b>) => array<'b> = "flatMap" +@send external flatMapWithIndex: (array<'a>, ('a, int) => array<'b>) => array<'b> = "flatMap" let findMap = (arr, f) => { let rec loop = i => diff --git a/src/Core__Array.resi b/src/Core__Array.resi index 7fb2aae5..5132dcab 100644 --- a/src/Core__Array.resi +++ b/src/Core__Array.resi @@ -968,6 +968,30 @@ Console.log( @send external flatMap: (array<'a>, 'a => array<'b>) => array<'b> = "flatMap" +/** +`flatMapWithIndex(array, mapper)` returns a new array concatenating the arrays returned from running `mapper` on all items in `array`. + +## Examples +```rescript +type language = ReScript | TypeScript | JavaScript + +let array = [ReScript, TypeScript, JavaScript] + +Console.log( + array->Array.flatMapWithIndex((item, index) => + switch item { + | ReScript => [index] + | TypeScript => [index, index + 1] + | JavaScript => [index, index + 1, index + 2] + } + ), +) +// [0, 1, 2, 2, 3, 4] +``` +*/ +@send +external flatMapWithIndex: (array<'a>, ('a, int) => array<'b>) => array<'b> = "flatMap" + /** `findMap(arr, fn)`