🚧Array.list(n)
💾 replit
// ⭐️ Array.list(n)
Array.list = function(n, {
start = 0,
step = 1,
} = {}) {
// initialize
let i = 0; // integer index
let value = start; // array item value
let arr = Array(n); // empty array
while (i < n) {
arr[i] = value; // set item value
value += step; // next value (increment by `step`)
i += 1; // next index
}
return arr;
};
💈範例:
Array.list(5), // [ 0, 1, 2, 3, 4 ]
Array.list(5, { start: 2 }), // [ 2, 3, 4, 5, 6 ]
Array.list(5, { start: 2, step: 3 }), // [ 2, 5, 8, 11, 14 ]
Array.list(5, { step: -1 }), // [ 0, -1, -2, -3, -4 ]
💾 replit
// ⭐️ arr1(n): Array(n).fill().map()
function arr1(n, {
start = 0
}={}){
return Array(n) // empty array (only set {length: n})
.fill() // ⭐️ set integer properties❗
.map((_, i) => i + start); // ⭐️ map over integer properties❗
}
// ⭐️ arr2(n): Array(n).keys()
function arr2(n, {
start = 0
}={}){
let arr = [ ...Array(n).keys() ];
return start == 0 ? arr : // [0, 1, 2, ..., n-1]
arr.map(i => i + start); // [start, start+1, ...]
}
// ⭐️ arr3(n): Array.from()
function arr3(n, {
start=0
}={}){
// passing map function to Array.from(),
// with an object with a `length` property
return Array.from({length: n}, (_, i) => i + start);
}
// ⭐️ arr4(n): while loop
function arr4(n, {
start=0
}={}){
let i = 0; // integer index
let value = start; // array item value
let arr = Array(n); // empty array
while(i < n){
arr[i] = value; // set item value
value += 1; // next value (increment by 1)
i += 1; // next index
}
return arr;
}
// ⭐️ measure
function measure(f, n){
let t1 = new Date().getTime();
f(n);
let t2 = new Date().getTime();
return t2 - t1;
// log(`${f.name}: ${t2 - t1} ms`);
}
// ⭐️ test k times
let k = 100;
(function(times){
let m = 100000; // array length
let sum = [0, 0, 0, 0];
let fs = [arr1, arr2, arr3, arr4];
let t1 = new Date().getTime();
for(let _ = 0; _ < times; _++){
fs.forEach((f, j) => sum[j] += measure(f, m));
}
let t2 = new Date().getTime();
log(`total time elapsed: ${(t2 - t1)/1000} sec`);
let avgs = sum.map(x => x/times);
log(avgs);
})(k);
// total time elapsed: 8.676 sec
//
// arr1 arr2 arr3 arr4⭐️
// ----------------------------
// [ 9.59, 28.67, 49.25, 3.39 ]
// [ 11.1, 24.41, 48.46, 2.76 ]
array.fill() - 沒填寫參數,表示 filled with
undefined
Last updated