🧵 Inserts a separator between each element of an array or characters of a string.
Info
The list can be an Array or a String.
Syntax
TypeScript
import { intersperse } from '@opentf/std'; intersperse( list: string | unknown[], sep: ((index: number) => unknown) | unknown ): string | unknown[]
Parameters
list: The source array or string.sep: The separator to insert. Can be a value or a function that returns a value based on the current index.
Returns
A new array or string with the separator interspersed.
Examples
TypeScript
const arr = [1, 2, 3]; intersperse(arr, '&') //=> [1, '&', 2, '&', 3] const menu = ['Home', 'Menu', 'Sub Menu']; intersperse(menu, '>') //=> [ // 'Home', // '>', // 'Menu', // '>', // 'Sub Menu', // ] intersperse('Hello', '-') //=> 'H-e-l-l-o' const items = [ { type: 'div', text: 'Apple' }, { type: 'div', text: 'Orange' }, { type: 'div', text: 'Mango' }, ]; intersperse(items, { type: 'br' }) //=> [ // { // type: 'div', // text: 'Apple', // }, // { // type: 'br', // }, // { // type: 'div', // text: 'Orange', // }, // { // type: 'br', // }, // { // type: 'div', // text: 'Mango', // }, // ] intersperse(['a', 'b', 'c'], (i) => `<span key="sep-${i}"> , </span>`) //=> [ // 'a', // '<span key="sep-0"> , </span>', // 'b', // '<span key="sep-1"> , </span>', // 'c', // ]