Skip to content

replaceOrAppend

Replace item in array or append if no match

193 bytes

Usage

Given an array of items, an item and an identity function, returns a new array with the item either replaced at the index of the existing item — if it exists, else it is appended at the end.

import * as _ from 'radashi'
const fish = [
{
name: 'Marlin',
weight: 105,
},
{
name: 'Salmon',
weight: 19,
},
{
name: 'Trout',
weight: 13,
},
]
const salmon = {
name: 'Salmon',
weight: 22,
}
const sockeye = {
name: 'Sockeye',
weight: 8,
}
_.replaceOrAppend(fish, salmon, f => f.name === 'Salmon') // => [marlin, salmon (weight:22), trout]
_.replaceOrAppend(fish, sockeye, f => f.name === 'Sockeye') // => [marlin, salmon, trout, sockeye]