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
import _
_from'radashi'
const
constfish: {
name:string;
weight:number;
}[]
fish= [
{
name: string
name: 'Marlin',
weight: number
weight: 105,
},
{
name: string
name: 'Salmon',
weight: number
weight: 19,
},
{
name: string
name: 'Trout',
weight: number
weight: 13,
},
]
const
constsalmon: {
name:string;
weight:number;
}
salmon= {
name: string
name: 'Salmon',
weight: number
weight: 22,
}
const
constsockeye: {
name:string;
weight:number;
}
sockeye= {
name: string
name: 'Sockeye',
weight: number
weight: 8,
}
import _
_.
replaceOrAppend<{
name:string;
weight:number;
}>(array:readonly {
name:string;
weight:number;
}[], newItem: {
name:string;
weight:number;
}, match: (a: {
name:string;
weight:number;
}, idx:number) =>boolean): {
name:string;
weight:number;
}[]
export replaceOrAppend
Replace the first occurrence of an item in an array where the
match function returns true. If no items match, append the new
item to the end of the list.
Replace the first occurrence of an item in an array where the
match function returns true. If no items match, append the new
item to the end of the list.