import type { Fn } from "@thi.ng/api" ; import { SEMAPHORE } from "@thi.ng/api/api" ; import type { Reducer , Transducer } from "./api.js" ; import { __iter , iterator } from "./iterator.js" ; import { isReduced } from "./reduced.js" ; example param fn param stateful export function partitionBy < T > ( fn , stateful ? ) ; export function partitionBy < T > ( fn , src ) ; export function partitionBy < T > ( fn , stateful , src ) ; export function partitionBy < T > ( ... args ) { return ( __iter ( partitionBy , args , iterator ) || ( ( [ init , complete , reduce ] ) => { const fn = args [ 0 ] ; const f = args [ 1 ] === true ? ( < ( ) => Fn < T , any > > fn ) ( ) : fn ; let prev = SEMAPHORE ; let chunk ; return < Reducer < any , T > > [ init , ( acc ) => { if ( chunk && chunk . length ) { acc = reduce ( acc , chunk ) ; chunk = null ; } return complete ( acc ) ; } , ( acc , x ) => { const curr = f ( x ) ; if ( prev === SEMAPHORE ) { prev = curr ; chunk = [ x ] ; } else if ( curr === prev ) { chunk ! . push ( x ) ; } else { chunk && ( acc = reduce ( acc , chunk ) ) ; chunk = isReduced ( acc ) ? null : [ x ] ; prev = curr ; } return acc ; } , ] ; } ) ) ; }