diff options
| author | Aya Morisawa <AyaMorisawa4869@gmail.com> | 2018-11-09 13:03:46 +0900 |
|---|---|---|
| committer | syuilo <Syuilotan@yahoo.co.jp> | 2018-11-09 13:03:46 +0900 |
| commit | 500fc47618014b17166ef928767f12c00257b080 (patch) | |
| tree | c3b86b06a7b0dc1f7dca48c09370f854b42d99e9 /src/prelude/array.ts | |
| parent | Use sum function (#3174) (diff) | |
| download | sharkey-500fc47618014b17166ef928767f12c00257b080.tar.gz sharkey-500fc47618014b17166ef928767f12c00257b080.tar.bz2 sharkey-500fc47618014b17166ef928767f12c00257b080.zip | |
Add group function (#3175)
Diffstat (limited to 'src/prelude/array.ts')
| -rw-r--r-- | src/prelude/array.ts | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/src/prelude/array.ts b/src/prelude/array.ts index 42f05dc0c9..8536e486d6 100644 --- a/src/prelude/array.ts +++ b/src/prelude/array.ts @@ -29,3 +29,19 @@ export function unique<T>(xs: T[]): T[] { export function sum(xs: number[]): number { return xs.reduce((a, b) => a + b, 0); } + +export function groupBy<T>(f: (x: T, y: T) => boolean, xs: T[]): T[][] { + const groups = [] as T[][]; + for (const x of xs) { + if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) { + groups[groups.length - 1].push(x); + } else { + groups.push([x]); + } + } + return groups; +} + +export function groupOn<T, S>(f: (x: T) => S, xs: T[]): T[][] { + return groupBy((a, b) => f(a) === f(b), xs); +} |