-
Notifications
You must be signed in to change notification settings - Fork 5
Custom Operators
Vitaly Tomilov edited this page Dec 1, 2022
·
42 revisions
In some cases you may want to create your own custom operator, by reusing an existing one, or by combining several existing operators. And here we show you how to do just that.
See also: iter-ops-extras - collection of complete operators.
When using a single existing operator, you can just forward into it:
import {aggregate, Operation} from 'iter-ops';
// joins strings with separator:
function join<T>(separator?: string): Operation<T, string> {
return aggregate(a => a.join(separator));
}
Usage example:
const i = pipe('word', join(','));
console.log(...i); //=> w,o,r,d
When using several existing operators, you need to return a callback with chain:
import {distinct, map, Operation} from 'iter-ops';
// selects unique key-values, then remaps into just values:
export function uniqueValues<T, R>(keySelector: (value: T, index: number) => R): Operation<T, R> {
return i => {
const k = distinct(keySelector)(i); // process + chain to the source iterator
return map(keySelector)(k); // process + chain to the previous iterator
}
}
Usage example:
const input: { value: number }[] = [{value: 1}, {value: 2}, {value: 3}, {value: 2}];
const i = pipe(input, uniqueValues(a => a.value)); //=> pick unique object-values, and return just values
console.log(...i); //=> 1 2 3