Looking for a way to create object Array that has a fixed size of 3 that fills it with default values but when i come to push into the array it should replace the default values.
Example:
Declare an array which fills the array with a string of "default value"
["default value", "default value", "default value"]
I now push some text to this initial array and expect the following:
["Added Data", "Default value", "Default Value"]
I push more data to this array and expect the following:
["Added Data", "Added Data", "Default Value"]
Again I push more data to this array and expect the following:
["Added Data", "Added Data", "Added Data"]
So the end result should be if push one data then the remainder of array should remain the default value unless i push all three data into the array.
Note: This example is a string array just to show an example but the solution i am looking for is array of objects. The Array.fill() method works great for JavaScript immutable values like strings, numbers, and booleans. Array with objects, each slot in the array refers to the same object which is not what i am looking for. I want each object to be unique
CodePudding user response:
You can extend the Array class to make it have the behavior you described...
class FixedArray extends Array {
/**
* Contruct a fixed-length Array
* @param int length - length of the array
* @param mixed default_value - The default value for empty slots
*/
constructor(length, default_value) {
super(length);
this.default_value = default_value;
super.fill(default_value);
}
/**
* "Push" items onto the begining of the array (unshift)
* @params ...args mixed - values to put in the array
*/
push(...args) {
args.forEach(arg => {
super.pop();
super.unshift(arg);
});
}
/**
* Pop an item off the end of the array
* and replace it with the default value
*/
pop(){
super.pop();
super.push(this.default_value);
}
/**
* Shift an item off the start of the array
* and replace it with the default value
*/
shift(){
super.shift();
super.unshift(this.default_value);
}
}
var arr = new FixedArray(4, 'default value');
console.log(arr);
arr.push('new value');
console.log(arr);
arr.push('new value');
console.log(arr);
arr.pop();
console.log(arr);
And to address the part about the array's fill method, you cna add a method to just copy whatever value you put in it...
/**
* Fill the array with copies of whatever arguments are provided.
* Fills by value, not by reference.
*/
fill(...args){
args.forEach(arg=>{
let copy = JSON.parse(JSON.stringify(arg));
this.push(arg);
});
}
CodePudding user response:
To create and fill the array with default unique object value:
const tuple = new Array(3).fill(0).map(() => ({ foo: "bar" }))
// or
const defaultObject = { foo: "bar" }
const tuple = new Array(3).fill(0).map(() => ({ …defaultObject }))
To add new item, and keep array size constant
function addTo(tuple, newItem) {
tuple.unshift(newItem) // add new item to beginning
tuple.pop() // remove old item at the end
}