Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snippets] add chunkArray function to array manipulation snippets #190

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions public/consolidated/javascript.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@
{
"name": "Array Manipulation",
"snippets": [
{
"title": "Chunk Array",
"description": "Splits an array into chunks based on a number.",
"author": "LuziferSenpai",
"tags": [
"array",
"partition",
"reduce"
],
"contributors": [],
"code": "function chunkArray(array, chunkSize) {\n if (!Array.isArray(array)) {\n throw new TypeError('Expected an array as the first argument.');\n }\n if (typeof chunkSize !== 'number' || chunkSize <= 0) {\n throw new RangeError('Chunk size must be a positive number.');\n }\n\n return array.reduce((chunks, item, index) => {\n const chunkIndex = Math.floor(index / chunkSize);\n\n if (!chunks[chunkIndex]) {\n chunks[chunkIndex] = [];\n }\n\n chunks[chunkIndex].push(item);\n\n return chunks;\n }, []);\n}\n\n// Usage:\nconst data = [1, 2, 3, 4, 5, 6, 7, 8];\nconst chunked = chunkArray(data, 3); // Returns: [[1, 2, 3], [4, 5, 6], [7, 8]]\n"
},
{
"title": "Partition Array",
"description": "Splits an array into two arrays based on a callback function.",
Expand Down
33 changes: 33 additions & 0 deletions snippets/javascript/array-manipulation/chunk-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
title: Chunk Array
description: Splits an array into chunks based on a number.
author: LuziferSenpai
tags: array,partition,reduce
---

```js
function chunkArray(array, chunkSize) {
if (!Array.isArray(array)) {
throw new TypeError('Expected an array as the first argument.');
}
if (typeof chunkSize !== 'number' || Number.isNaN(chunkSize) || chunkSize <= 0) {
throw new RangeError('Chunk size must be a positive number.');
}

return array.reduce((chunks, item, index) => {
const chunkIndex = Math.floor(index / chunkSize);

if (!chunks[chunkIndex]) {
chunks[chunkIndex] = [];
}

chunks[chunkIndex].push(item);

return chunks;
}, []);
}

// Usage:
const data = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArray(data, 3); // Returns: [[1, 2, 3], [4, 5, 6], [7, 8]]
```