When I am adding elements to an array, only the last element is added to the array? I cant find out what is wrong in the closure.
const data = require('../content/data')
function randomize() {
const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
let name_index = 0
let origin_city_index = 0
let destination_city_index = 0
let org_message = {
name: '',
origin: '',
destination: ''
}
let ds = [];
return function getDs() {
for(let i = 0; i< ds_size; i++) {
name_index = Math.floor(Math.random() * data.names.length)
origin_city_index = Math.floor(Math.random() * data.cities.length)
destination_city_index = Math.floor(Math.random() * data.cities.length)
org_message.name = data.names[name_index]
org_message.origin = data.cities[origin_city_index]
org_message.destination = data.destination[destination_city_index]
ds.push(org_message)
}
return ds
}
}
module.exports = {randomize}
You are reusing the same org_message object for every entry in the array so all the array elements will point at exactly the same object (however you last modified the object) and thus will all contain the exact same thing.
Instead, create a new object for each iteration of the loop so each element of the array contains its own object. In Javascript objects are passed to functions, returned from functions or inserted into arrays as pointers, not copies. So, ds.push(org_message) just pushes a pointer to org_message into the array, thus you must create a new object for each element of the array if you want them to all be different.
const data = require('../content/data')
function randomize() {
const ds_size = Math.floor(Math.random() * 500) + 50 //Generate no of objects in stream
let name_index = 0
let origin_city_index = 0
let destination_city_index = 0
return function getDs() {
let ds = [];
for(let i = 0; i< ds_size; i++) {
let org_message = {
name: '',
origin: '',
destination: ''
};
name_index = Math.floor(Math.random() * data.names.length)
origin_city_index = Math.floor(Math.random() * data.cities.length)
destination_city_index = Math.floor(Math.random() * data.cities.length)
org_message.name = data.names[name_index]
org_message.origin = data.cities[origin_city_index]
org_message.destination = data.destination[destination_city_index]
ds.push(org_message)
}
return ds
}
}
module.exports = {randomize}
I also moved the declaration of ds inside the returned function because without that, you will be reusing the same ds array each time the returned function is called which will just be adding more elements to the end of the same array and it will be modifying the array that was returned on previous calls.
Please remember that objects in Javascript are used by pointer so passing one or returning one passes a pointer to the object - the object is not copied.