just icon indicating copy to clipboard operation
just copied to clipboard

Package Idea: array upsert

Open TClark1011 opened this issue 2 years ago • 2 comments

An idea for a new package: An "upsert" function for arrays. This would be based on the "upsert" operation commonly used in databases, which is a combination of "update" and "insert", however, we would adapt it to fit better for use with arrays.

You would call the function similar to this:

upsert([1,2,3,4], 2, -1) // [1,2,-1,4]
upsert(["a","b","c"], 6, "d") // ["a","b","c","d"]

The idea is that you pass an array, and index that you want to "upsert" into, and the element which you want to be "upserted". If the provided index is within the bounds of the array, then the provided item will replace the item at that index. If the provided index is outside the bounds of the provided index, then it gets pushed onto the end of the array.

I can't really say for sure how much a function like this would be used/needed, I just thought I would suggest it since I had to write my own version of it for a recent project.

TClark1011 avatar Aug 02 '22 22:08 TClark1011

Hi Thomas, thanks for the suggestion. My first thought was you could achieve the same with Array#splice. But that said, splice mutates and does not return the updated value. So yes I think this has value!

angus-c avatar Aug 06 '22 21:08 angus-c

Permission to work on this?

Lucky-victory avatar Sep 15 '22 10:09 Lucky-victory