Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions array.libsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,18 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet';
for i in std.range(0, std.length(arr) - 1)
if filter_func(i, arr[i])
],

'#chunkArray':: d.fn(
|||
`chunkArray` chunks an array into smaller arrays of the given max size.
|||,
[
d.arg('arr', d.T.array),
d.arg('maxSize', d.T.number),
]
),
chunkArray(arr, maxSize): [
arr[i * maxSize:std.min((i + 1) * maxSize, std.length(arr))]
for i in std.range(0, std.ceil(std.length(arr) / maxSize) - 1)
],
}
10 changes: 10 additions & 0 deletions docs/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,21 @@ local array = import "github.com/jsonnet-libs/xtd/array.libsonnet"

## Index

* [`fn chunkArray(arr, maxSize)`](#fn-chunkarray)
* [`fn filterMapWithIndex(filter_func, map_func, arr)`](#fn-filtermapwithindex)
* [`fn slice(indexable, index, end='null', step=1)`](#fn-slice)

## Fields

### fn chunkArray

```ts
chunkArray(arr, maxSize)
```

`chunkArray` chunks an array into smaller arrays of the given max size.


### fn filterMapWithIndex

```ts
Expand Down
30 changes: 30 additions & 0 deletions test/array_test.jsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ local array = import '../array.libsonnet';
local test = import 'github.com/jsonnet-libs/testonnet/main.libsonnet';

local arr = std.range(0, 10);
local mixedArr = ['a', 1, 'b', 2, 'c', 3, 4, 5, 6, 7, 8, 9, 'd', 'e', 'f', 'g', 'h', 'i', 'j'];

test.new(std.thisFile)

Expand Down Expand Up @@ -81,3 +82,32 @@ test.new(std.thisFile)
expected=[0, 2, 4],
)
)

+ test.case.new(
name='chunkArray',
test=test.expect.eq(
actual=array.chunkArray(mixedArr, maxSize=3),
expected=[['a', 1, 'b'], [2, 'c', 3], [4, 5, 6], [7, 8, 9], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j']],
)
)
+ test.case.new(
name='chunkArray - maxSize is 2',
test=test.expect.eq(
actual=array.chunkArray(mixedArr, maxSize=2),
expected=[['a', 1], ['b', 2], ['c', 3], [4, 5], [6, 7], [8, 9], ['d', 'e'], ['f', 'g'], ['h', 'i'], ['j']],
)
)
+ test.case.new(
name='chunkArray - maxSize is larger than array length',
test=test.expect.eq(
actual=array.chunkArray(mixedArr, maxSize=100),
expected=[mixedArr],
)
)
+ test.case.new(
name='chunkArray - maxSize is 1',
test=test.expect.eq(
actual=array.chunkArray(mixedArr, maxSize=1),
expected=[['a'], [1], ['b'], [2], ['c'], [3], [4], [5], [6], [7], [8], [9], ['d'], ['e'], ['f'], ['g'], ['h'], ['i'], ['j']],
)
)
Loading