Skip to content
Open
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 docs.json

Large diffs are not rendered by default.

38 changes: 36 additions & 2 deletions src/Array/Extra.elm
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module Array.Extra exposing
( all, any, member
, reverse, intersperse, update, pop, removeAt, insertAt
, reverse, intersperse, update, pop, removeAt, insertAt, splice
, removeWhen, filterMap
, sliceFrom, sliceUntil, splitAt, unzip
, interweave_, andMap, map2, map3, map4, map5, zip, zip3
Expand All @@ -18,7 +18,7 @@ module Array.Extra exposing

# Alter

@docs reverse, intersperse, update, pop, removeAt, insertAt
@docs reverse, intersperse, update, pop, removeAt, insertAt, splice


# Filtering
Expand Down Expand Up @@ -689,6 +689,40 @@ insertAt index elementToInsert array =
array


{-| Start at an index, and remove a number of elements, and replace them with new elements.

import Array exposing (fromList)

fromList [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
|> splice 2 3 (always (fromList [ 10, 11, 12 ]))
--> fromList [ 1, 2, 10, 11, 12, 6, 7, 8, 9 ]

Handy for mapping over a subset of an array.

fromList [ 1, 2, 3, 4, 5 ]
|> splice 2 100 (Array.map (\n -> n + 10))
--> fromList [ 1, 2, 13, 14, 15 ]

The index can be negative, counting from the end.

fromList [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
|> splice -4 3 (always (fromList []))
--> fromList [ 1, 2, 3, 4, 5, 9]

-}
splice : Int -> Int -> (Array a -> Array a) -> Array a -> Array a
splice startIndex removeCount spliceFunction array =
let
rc =
max 0 removeCount
in
Array.append
(Array.append (Array.slice 0 startIndex array)
(spliceFunction (Array.slice startIndex (startIndex + rc) array))
)
(Array.slice (startIndex + rc) (Array.length array) array)
Copy link
Collaborator

@lue-bird lue-bird Jan 23, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since startIndex can be negative, this slice start can get non-negative and therefore incorrectly add additional elements.

In general, tests would be cool



{-| Whether all elements satisfy a given test.

import Array exposing (fromList, empty)
Expand Down