๐ง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 ]
ไฝฟ็จๆนๆณ
่ทๅ (ms)
Array(n).fill().map()
10
[ ...Array(n).keys() ].map()
26
Array.from()
49
while
loop
3 ๐
๐พ 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