import { identity } from './functions' ; import { isArrayLike } from './object' ; type Tuple < T > = [ T ? , T ? ] ; /** Split array into tuples */ export const tuple = < T > ( arr ) : Tuple < T > [ ] => arr . reduce ( ( acc , el ) => { if ( acc . length === 0 || acc [ acc . length - 1 ] . length >= 2 ) acc . push ( [ ] ) ; acc [ acc . length - 1 ] . push ( el ) ; return acc ; } , [ ] ) ; /** Flat array - unwraps one level of nested arrays */ export const flat = < T > ( arr ) : T [ ] => arr . reduce ( ( acc , el ) => el ? acc . concat ( el ) : acc , [ ] ) as T [ ] ; /** Wraps passed object or primitive to array */ export const wrap = < T > ( arr ) : T [ ] => { if ( arr === undefined || arr === null ) return [ ] ; if ( Array . isArray ( arr ) ) return arr ; return [ arr ] ; } ; /** Unwraps and returns the first element if passed object is array-like, returns original object otherwise */ export function unwrap ( value ) ; export function unwrap < T > ( value ) ; export function unwrap < T extends Node > ( value ) ; export function unwrap ( value ) ; export function unwrap ( value ) { return isArrayLike ( value ) ? value [ 0 ] : value ; } /** Makes array values unique */ export const uniq = < T > ( arr ) : T [ ] => { const result = [ ] ; const set = new Set < T > ( ) ; arr . forEach ( ( item ) => set . add ( item ) ) ; set . forEach ( ( item ) => result . push ( item ) ) ; return result ; } ; /** Create an array filled with the range [0,..,N-1] */ export function range ( n ) ; /** Create an array filled with values returned by the filler callback */ export function range < T > ( n , filler ) ; export function range ( n , filler = identity ) { const arr = Array ( n ) ; let i = 0 ; while ( i < n ) arr [ i ] = filler ( i ++ ) ; return arr ; } returns export const groupBy = < T , V extends string | number > ( array , group ) : Record < V , T [ ] > => { return array . reduce ( ( obj , el ) => { const key = group ( el ) ; obj [ key ] ? obj [ key ] . push ( el ) : obj [ key ] = [ el ] ; return obj ; } , { } as Record < V , T [ ] > ) ; } ;