Skip to content

Instantly share code, notes, and snippets.

@aoitaku
Last active May 30, 2022 19:32
Show Gist options
  • Save aoitaku/212b6d9a0cc2e49dbd6eb337827c07c6 to your computer and use it in GitHub Desktop.
Save aoitaku/212b6d9a0cc2e49dbd6eb337827c07c6 to your computer and use it in GitHub Desktop.
chunkBy mixin for lodash
/// <reference path='typings/index.d.ts' />
import * as _ from 'lodash'
declare module 'lodash' {
// tslint:disable-next-line:interface-name
interface LoDashStatic {
chunkBy <T> (array: T[], predicate: (element: T) => boolean): T[][]
}
}
_.mixin({
chunkBy <T> (array: T[], predicate: (element: T) => boolean): T[][] {
return array.reduce((prev: T[][], current, index) => {
if (prev.length === 0 || predicate(current)) {
prev.push([current])
} else {
prev[prev.length - 1].push(current)
}
return prev
}, [])
},
}, { chain: false })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment