Skip to content

Commit

Permalink
feat: support chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
haoziqaq committed Nov 4, 2024
1 parent fd27210 commit 80e4419
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/.vitepress/items/array.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const arrayItems = [
{ text: 'at', link: '/array/at' },
{ text: 'chunk', link: '/array/chunk' },
{ text: 'uniq', link: '/array/uniq' },
{ text: 'uniqBy', link: '/array/uniq-by' },
{ text: 'find', link: '/array/find' },
Expand Down
24 changes: 24 additions & 0 deletions docs/array/chunk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# chunk

Chunking an `array`. The passed `size` indicates the length of the chunk.

### Usage

```ts
import { chunk } from 'rattail'

chunk([1, 2, 3], 2) // return [[1, 2], [3]]
```

### Arguments

| Arg | Type | Defaults |
| ------ | -------- | -------- |
| `arr` | `Array` | |
| `size` | `number` | `1` |

### Return

| Type |
| ------- |
| `Array` |
24 changes: 24 additions & 0 deletions docs/zh/array/chunk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# chunk

`数组` 进行分块。传递的 `size` 表示块的长度。

### 使用

```ts
import { chunk } from 'rattail'

chunk([1, 2, 3], 2) // return [[1, 2], [3]]
```

### 参数

| 参数 | 类型 | 默认值 |
| ------ | -------- | ------ |
| `arr` | `Array` | |
| `size` | `number` | `1` |

### 返回值

| 类型 |
| ------- |
| `Array` |
15 changes: 15 additions & 0 deletions src/array.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isArray } from './general'
import { clamp } from './number'

export function uniq<T>(arr: T[]) {
return [...new Set(arr)]
Expand Down Expand Up @@ -80,3 +81,17 @@ export function shuffle<T>(arr: T[]): T[] {
}
return arr
}

export function chunk<T>(arr: T[], size = 1): T[][] {
size = clamp(size, 1, arr.length)

const result: T[][] = []
let index = 0

while (index < arr.length) {
result.push(arr.slice(index, index + size))
index += size
}

return result
}
10 changes: 10 additions & 0 deletions tests/array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
find,
at,
shuffle,
chunk,
} from '../src'

it('uniq', () => {
Expand Down Expand Up @@ -84,3 +85,12 @@ it('shuffle', () => {
const shuffled = shuffle([...arr])
expect(shuffled.sort()).toEqual(arr)
})

it('chunk', () => {
expect(chunk([])).toEqual([])
expect(chunk([1, 2, 3, 4, 5])).toEqual([[1], [2], [3], [4], [5]])
expect(chunk([1, 2, 3, 4, 5], 0)).toEqual([[1], [2], [3], [4], [5]])
expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]])
expect(chunk([1, 2], 2)).toEqual([[1, 2]])
expect(chunk([1, 2], 3)).toEqual([[1, 2]])
})

0 comments on commit 80e4419

Please sign in to comment.