Skip to main content

Function: intersperse()

intersperse<ElementType>(iterable: IterableResolvable<ElementType>, separator: ElementType): IterableIterator<ElementType>

Creates a new iterator which places separator between adjacent items of the original iterator.

Type Parameters

Type Parameter
ElementType

Parameters

ParameterTypeDescription
iterableIterableResolvable<ElementType>An iterator to map over.
separatorElementTypeThe separator to place between adjacent items.

Returns

IterableIterator<ElementType>

Examples

import { intersperse } from '@sapphire/iterator-utilities';

const iterable = [0, 1, 2];
console.log([...intersperse(iterable, 100)]);
// Output: [0, 100, 1, 100, 2]

intersperse can be very useful to join an iterator's items using a common element:

import { intersperse } from '@sapphire/iterator-utilities';

const iterable = ['Hello', 'World', '!'];
console.log([...intersperse(iterable, ', ')].join(''));
// Output: 'Hello, World, !'

Defined in

projects/utilities/packages/iterator-utilities/src/lib/intersperse.ts:29