loadsh函式庫中的 chunk 函式采用 typescript 語法重寫.
chunk 函式
將陣列(array)拆分成多個 size 長度的區塊,并將這些區塊組成一個新陣列,
如果array 無法被分割成全部等長的區塊,那么最后剩余的元素將組成一個區塊,
/**
*
* 將陣列(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); // []
個人作品
ip定位查詢瀏覽器插件
老虎優惠券瀏覽器插件
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/245606.html
標籤:其他
上一篇:JavaScript(六)-函式
