import { HashHelper } from './hash.helper'; export class ArrayHelper { public static chunks( array: Array | null, n: number | null ): Array> | null { if (!array) { return null; } if (!n) { return null; } return array.reduce((array, item, index) => { const chunkIndex: number = Math.floor(index / n); if (!array[chunkIndex]) { array[chunkIndex] = []; } array[chunkIndex].push(item); return array; }, [] as Array>); } public static distinct( array: Array | null, fn: (x: T) => any ): Array | null { if (!array) { return null; } return array.filter((x: T, index: number, self: Array) => { const item = self.find((y: T) => fn(y) === fn(x)); if (!item) { return false; } return self.indexOf(item) === index; }); } public static fromCsv(content: string | null): Array | null { if (!content) { return null; } const lines: Array = content.split('\n'); const headerLine: string = lines[0]; const columns: Array = headerLine.split(','); return lines.splice(1).reduce((array, x) => { const obj = {} as { [key: string]: string }; for (let index = 0; index < columns.length; index++) { obj[columns[index]] = x.split(',')[index]; } array.push(obj); return array; }, [] as Array<{ [key: string]: string }>); } public static group(array: Array, fn: (x: T) => any): Array> { const dict = {} as { [key: string]: Array }; for (const x of array) { const key: string | null = HashHelper.fromObject(fn(x)); if (!key) { continue; } if (!dict[key]) { dict[key] = []; } dict[key].push(x); } return Object.keys(dict).map((key: string) => dict[key]); } public static repeat(item: T, n: number): Array { const array: Array = []; for (let i = 0; i < n; i++) { array.push(item); } return array; } }