I was trying to merge & add these two objects like this :
obj1 = {
jpg: 1,
gif: 3,
}
obj2 = {
jpg: 1,
avi: 5,
}
obj3 = mergeAdd(obj1, obj2);
// obj3 = {
// jpg: 2,
// gif: 3,
// avi: 5,
// }
First, I create this which takes O(n^2) likes :
for (let foo in obj1) {
for (let bar in obj2) {
if (foo === bar) {
// Exists : Add count
obj1[bar] += obj2[bar];
} else {
// Don`t Exists : Copy from obj2
obj1[bar] = obj2[bar];
}
}
}
And then, one 'new idea' came into my mind - using hash function :
- Get hash value for 'key' of obj1 & obj2.
- Insert or add 'value' of obj1 & obj2 to new array using their hash value as an index of the array.
- Make the array into new object.
What I want to know :
- Is there any library which have function like mergeAdd(obj1, obj2)?
- Is my 'new idea' faster than mergeAdd(obj1, obj2)?
- What is the fastest algorithm to do mergeAdd?
Thanks!