Skip to content

Commit

Permalink
feat(transducers): add length() transducer
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 20, 2023
1 parent 755ca21 commit 47a95b7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/transducers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export * from "./interpolate-linear.js";
export * from "./interpose.js";
export * from "./keep.js";
export * from "./labeled.js";
export * from "./length.js";
export * from "./map-deep.js";
export * from "./map-indexed.js";
export * from "./map-keys.js";
Expand Down
33 changes: 33 additions & 0 deletions packages/transducers/src/length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { isIterable } from "@thi.ng/checks/is-iterable";
import type { Transducer } from "./api.js";
import { iterator1 } from "./iterator.js";
import { map } from "./map.js";
import type { ILength } from "@thi.ng/api";

/**
* Similar to `map((x) => x.length)`. A transducer which returns the `.length`
* of each input (optionally with offset `n` added, default: 0) and yields
* sequence of these values.
*
* @example
* ```ts
* [...length(0, ["a", "bc", "def"])]
* // [1, 2, 3]
* ```
*
* @param n - optional offset
*/
export function length(n?: number): Transducer<ILength, number>;
export function length(
n: number,
src: Iterable<ILength>
): IterableIterator<number>;
export function length(n = 0, src?: Iterable<ILength>): any {
return isIterable(src)
? iterator1(length(n), src)
: map(
n === 0
? (x: ILength) => x.length
: (x: ILength) => x.length + n
);
}

0 comments on commit 47a95b7

Please sign in to comment.