// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each subarray is of length size
// --- Examples
// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

function chunk(array, size) {
let result = [];
let temp = [];
const len = array.length;
for (let i = 0; i < len; i++) {
let mod = i % size;
if (mod === 0) {
if (temp.length !== 0) {
result = [...result, temp];
}
temp = [];
} temp[mod] = array[i];
} result = [...result, temp]; return result;
}

way 2:

function chunk(array, size) {
let chunked = [];
let index = 0; while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
} return chunked;
}

test:

const chunk = require("./index");

test("function chunk exists", () => {
expect(typeof chunk).toEqual("function");
}); test("chunk divides an array of 10 elements with chunk size 2", () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunked = chunk(arr, 2); expect(chunked).toEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]);
}); test("chunk divides an array of 3 elements with chunk size 1", () => {
const arr = [1, 2, 3];
const chunked = chunk(arr, 1); expect(chunked).toEqual([[1], [2], [3]]);
}); test("chunk divides an array of 5 elements with chunk size 3", () => {
const arr = [1, 2, 3, 4, 5];
const chunked = chunk(arr, 3); expect(chunked).toEqual([[1, 2, 3], [4, 5]]);
}); test("chunk divides an array of 13 elements with chunk size 5", () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const chunked = chunk(arr, 5); expect(chunked).toEqual([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]);
});

最新文章

  1. ok
  2. C#对七牛云的操作
  3. Java设计模式(七) 模板模式
  4. 从Sql server 2008获取表字段属性信息,注释信息
  5. windows系统调用 利用事件对象实现进程通信
  6. 实现快速迭代的引擎设计 - Capcom RE Engine的架构与实现
  7. c# params
  8. 【锋利的JQuery-学习笔记】添加提示图片
  9. 关于ref与out的区别
  10. Git客户端使用
  11. mysql基础: mysql列类型--字符串
  12. 字符转十六进制 String =&gt; HEX using &quot;hexdump&quot; on linux
  13. Chapter 2 Open Book&mdash;&mdash;13
  14. java.text.DateFormat 多线程并发问题
  15. centos7安装Jenkins更改默认端口并配置Ldap服务器进行用户认证
  16. 项目复审——Beta阶段
  17. VSCode集成TypeScript编译
  18. 用localStorage来存储数据的一些经验
  19. linux pmap命令
  20. 怎样绕开QQ通讯录和360的广播中断

热门文章

  1. java获取单张网页中img标签中的src
  2. Netty的学习
  3. class CAdoInterface
  4. 剑指offer49:把字符串转换成整数
  5. PHP内存管理-zendMM
  6. 对Python中print函数参数的认识
  7. Docker pull 出现的 error pulling image configuration: Get https://dseasb33srnrn.cloudfront.net/
  8. 贝叶斯优化 Bayesian Optimization
  9. Java Web-servlet、HTTP in servlet和捎带的Java绘图学习
  10. HTML给标题栏添加图标