Lodash function library — chunk

Time：2021-12-30

In the loadsh Library`chunk`Function adoption`typescript`Grammar rewriting

`chunk`function
Array（`array`）Split into multiple`size`And form these blocks into a new array.
If`array`If it cannot be divided into blocks of equal length, the last remaining elements will form a block.

``````/**
*
*Split the array into multiple size length blocks, and form these blocks into a new array.
*If the array cannot be divided into all equal length blocks, the last remaining elements will form a block.
*
*@ param array array to be processed
*@ param size length of each array block
* @returns {Array>}
* @example
*
* chunk(['a', 'b', 'c'], 2)
* // => [['a', 'b'], ['c']]
*
* chunk(['a', 'b', 'c','d'], 2)
* // => [['a', 'b'], ['c','d']]
*/
const chunk = (array: Array, size = 1): Array> => {
//Boundary detection
//Consider block lengths less than 1 and empty arrays
const length = array.length;
if (!length || size < 1) return [];

let index = 0; //  Processing array start bit
let resindex = 0; //  New array start bit
const result = new Array>(Math.ceil(length / size));
while (index < length) {
result[resindex++] = array. slice(index, (index += size)); //  Size is the step value
}
return result;
};

export default chunk;``````
``````import chunk from "../src/chunk";

const arr = [1, 2, 3, 4, 5, 6];
const n = chunk(arr, 3);
console.log(n); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

const arrs = ["a", "b", "c"];
const n1 = chunk(arrs, 2);
console.log(n1); // [ [ 'a', 'b' ], [ 'c' ] ]

const arre = [] as Array;
const n2 = chunk(arre, 2);
console.log(n2); // []``````

Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]