Skip to content

map

Transforms each value emitted by the source with a mapping function, and emits the result unless it equals the one already held.

The comparison is Object.is unless equals says otherwise, so a result that did not change wakes nothing below. To pass on every result — an event turned into a value, say — give equals: () => false, or use mapTo. The mapping function receives the value alone; withIndex attaches an index.

Timeline of observable events13467
map((x) => x % 2)
Timeline of observable events101
// Timeline:
//
// num$ 1 3 4 6 7
// parity$ 1 0 1
//
// Explanation:
// - map transforms each value
// - A result equal to the one held is not emitted
const num$ = source<number>();
const parity$ = num$.pipe(map((x) => x % 2));
const valueHistory: number[] = [];
parity$.subscribe((p) => {
valueHistory.push(p);
});
num$.next(1); // 1
num$.next(3); // still 1: not emitted
num$.next(4); // 0
num$.next(6); // still 0: not emitted
num$.next(7); // 1
assert.deepStrictEqual(valueHistory, [1, 0, 1]);

View source on GitHub