zoukankan      html  css  js  c++  java
  • [Algorithm] Chunk Array

    // --- 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]]);
    });
  • 相关阅读:
    easyui loadFilter 使用
    控件setText与setValue赋值顺序先后区别
    JS选中和取消选中checkbox
    easyui 解决连弹两个dialog时候,第二个dialog居中问题
    bootstrap基础学习【导航条、分页导航】(五)
    bootstrap基础学习【菜单、按钮、导航】(四)
    sublime设置
    《啊哈!算法》笔记
    《编码的奥秘》笔记
    Effective Objective-C 2.0 — 第14条:理解“类对象“的用意
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10960776.html
Copyright © 2011-2022 走看看