Is it possible, in Javascript, to create an array whose length is guaranteed to remain the same?
For example, the array A is created with length 2. Subs
We can use closure for this type of problem. We are just fixed the array size and return a function from a function.
function setArraySize(size){
return function(arr, val) {
if(arr.length == size) {
return arr;
}
arr.push(val);
return arr;
}
}
let arr = [];
let sizeArr = setArraySize(5); // fixed value for fixed array size.
sizeArr(arr, 1);
sizeArr(arr, 2);
sizeArr(arr, 3);
sizeArr(arr, 4);
sizeArr(arr, 5);
sizeArr(arr, 6);
console.log('arr value', arr);