Skip to content

replaceOrAppend

Replace item in array or append if no match

193 bytes
since v12.1.0

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
import _
_
from 'radashi'
const
const fish: {
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
const salmon: {
name: string;
weight: number;
}
salmon
= {
name: string
name
: 'Salmon',
weight: number
weight
: 22,
}
const
const sockeye: {
name: string;
weight: number;
}
sockeye
= {
name: string
name
: 'Sockeye',
weight: number
weight
: 8,
}
import _
_
.
function 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;
}[]

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.

@seehttps://radashi.js.org/reference/array/replaceOrAppend

@example

replaceOrAppend([1, 2, 3], 4, (n) => n > 1)
// [1, 4, 3]
replaceOrAppend([1, 2, 3], 4, (n) => n > 100)
// [1, 2, 3, 4]

@version12.1.0

replaceOrAppend
(
const fish: {
name: string;
weight: number;
}[]
fish
,
const salmon: {
name: string;
weight: number;
}
salmon
,
f: {
name: string;
weight: number;
}
f
=>
f: {
name: string;
weight: number;
}
f
.
name: string
name
=== 'Salmon') // => [marlin, salmon (weight:22), trout]
import _
_
.
function 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;
}[]

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.

@seehttps://radashi.js.org/reference/array/replaceOrAppend

@example

replaceOrAppend([1, 2, 3], 4, (n) => n > 1)
// [1, 4, 3]
replaceOrAppend([1, 2, 3], 4, (n) => n > 100)
// [1, 2, 3, 4]

@version12.1.0

replaceOrAppend
(
const fish: {
name: string;
weight: number;
}[]
fish
,
const sockeye: {
name: string;
weight: number;
}
sockeye
,
f: {
name: string;
weight: number;
}
f
=>
f: {
name: string;
weight: number;
}
f
.
name: string
name
=== 'Sockeye') // => [marlin, salmon, trout, sockeye]