loadsh函數庫中的 chunk
函數採用 typescript
語法重寫.html
chunk
函數
將數組(array
)拆分紅多個 size
長度的區塊,並將這些區塊組成一個新數組。
若是array
沒法被分割成所有等長的區塊,那麼最後剩餘的元素將組成一個區塊。typescript
/** * * 將數組(array)拆分紅多個 size 長度的區塊,並將這些區塊組成一個新數組。 * 若是array 沒法被分割成所有等長的區塊,那麼最後剩餘的元素將組成一個區塊。 * * @param array 須要處理的數組 * @param size 每一個數組區塊的長度 * @returns {Array<Array<T>>} * @example * * chunk(['a', 'b', 'c'], 2) * // => [['a', 'b'], ['c']] * * chunk(['a', 'b', 'c','d'], 2) * // => [['a', 'b'], ['c','d']] */ const chunk = <T>(array: Array<T>, size = 1): Array<Array<T>> => { // 邊界檢測 // 須要考慮塊長度小於1和空數組 const length = array.length; if (!length || size < 1) return []; let index = 0; // 處理數組起始位 let resindex = 0; // 新數組起始位 const result = new Array<Array<T>>(Math.ceil(length / size)); while (index < length) { result[resindex++] = array.slice(index, (index += size)); // size 爲步長值 } 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<string>; const n2 = chunk(arre, 2); console.log(n2); // []