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]]);
    });
  • 相关阅读:
    什么是CDN?哪些是流行的jQuery CDN?使用CDN有什么好处?
    jQuery 中$.get()和$.post()提交有区别吗?
    window.onload()函数和jQuery中的document.ready()区别
    js相等(==)与全等(===)的区别
    用javascript改变onclick调用的函数
    null,undefined,undeclared的区别
    JavaScript重定向到其他网页
    C Programing Environment
    转:JMir——Java版热血传奇2之资源文件与地图
    PHP内容管理项目函数列表
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10960776.html
Copyright © 2011-2022 走看看