Duplication of items in a Javascript Set - javascript

I was going through basics of Javscript Set.According to its defintion, A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
But I see when it comes to reference types the behavior is different. Consider the following snippet:
let set = new Set();
let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);
console.log("Scenario 1");
for (let user of set) {
console.log(user.name);
}
let set1 = new Set();
set1.add({ name: "John" });
set1.add({ name: "Pete" });
set1.add({ name: "Mary" });
set1.add({ name: "John" });
console.log("Scenario 2");
for (let user of set1) {
console.log(user.name);
}
I see in the scenario 1, it wont allow duplicates to be added as they are the same references. But in scenario 2 I see duplicates are being added.
Can some explain this behavior? Or Am I missing something.
How scenario 1 is different from 2?

Try doing a check of {name: 'John'} === {name: 'John'}. You would find it returns false.
Every new object has a different reference even though the contents can be same. If it gives false to you, the Set would consider it a different element too.
When you assign a variable with a Reference value, its memory location gets copied.
For example:
let john = {name: 'John'} // lets say memory: XYZ
So, every time when you do: set.add(john);, you are adding the memory location in the set. So, the Set would see you adding XYZ everytime and it won't accept duplicates.
In the second case,
When you do:
`set1.add({ name: "John" });` // You added maybe XYF
`set1.add({ name: "John" });` // You added maybe XYN
So, your Set treats them differently and adds both of them.

A Set does not look at the contents of the object itself. It only looks at the pointer to the object.
If it's not a pointer to the same physical object, then it's allowed to be added to the Set as a different physical object. In fact, you can add an object to the set and then change it's contents afterwards because the fact that it's in the set has NOTHING to do with the contents of the object, only the physical pointer to the object. If it's not the same pointer to the same object, then it can be added separately.
Here's an example:
let s = new Set();
let x1 = {name: "John"};
let x2 = {name: "John"};
console.log(x1 === x2); // false, not the same physical object
s.add(x1);
console.log(s.has(x1)); // true
console.log(s.has(x2)); // false
s.add(x2);
console.log(s.has(x2)); // true
console.log(Array.from(s)); // [{name: "John"}, {name: "John"}];
// now modify x1
x1.name = "Bob";
// the x1 object is still in the set, even though you modified it
// because being in the set has NOTHING to do with the contents of the object at all
console.log(s.has(x1)); // true
console.log(Array.from(s)); // [{name: "Bob"}, {name: "John"}];

Related

Developer Tools Console showing only final values

I have the following code that I run in the console:
// cache the starting array - 50 elements
let asTheyWere = selDocument.fields.field;
// create the new object
let nf = {};
$j.each(selDocument.fields.field[selDocument.fields.field.length - 1], function(a, b){
nf[a] = b;
});
// make a change and add the object to the array
for(i = 0; i < 5; i++) {
nf.name = `test me ${i}`;
// console.log(nf.name) shows 'test me 0', 'test me 1' ... 'test me 4'
selDocument.fields.field.push(nf);
}
// assign the array to a new variable - now at 55 elements
let asTheyAre = selDocument.fields.field;
// check the values
console.log(asTheyWere);
console.log(asTheyAre);
I know that the console doesn't update until the code is finished, so all variables are logged with their final value. I had thought that using different variables would avoid that, but asTheyWere and asTheyAre are the same, showing 55 elements (the first should have 50), AND the values appended to the end of the array are all the same as well: they should be 'test me 0', 'test me 1', 'test me 2' and so on, but they're all 'test me 4'.
When it's all done, then running
> console.log(selDocument.fields.field)
shows 'test me 4' on all added items, so it's not just the logging.
What's going on? How can I watch the progress and see accurate values, and get the right values appended to the array?
Even though they are different variables, they are still pointing to the same value. For example:
const foo = ['hello']
const bar = foo
foo[0] = 'goodbye'
console.log(bar[0]) // prints "goodbye"!
This happens because when you assign bar = foo, you aren't actually creating a copy of foo. Instead, you're saying, this variable bar is just another name used to refer to the contents of foo.
You could try cloning the original object to compare it to the new one. If the object is comprised of simple data, you can clone it like this:
const asTheyWere = JSON.parse(JSON.stringify(selDocument.fields.field));
// Make your changes...
const asTheyAre = selDocument.fields.field;
console.log(asTheyWere);
console.log(asTheyAre);

How references of the same object can't be equal?

Eg.:
let userOne = {
name: "Test",
surname: "Test"
}
let userTwo = {
...userOne
}
console.log(userOne === userTwo); // false
But, eg.:
console.log(userOne.name === userTwo.name); // true
So userOne and userTwo are two refeneces of the same object but console.log(userOne === userTwo); returns fasle.
Why is it?
Modification:
Ok. In the previous example there are two object. But what about this:
let userOne = {
name: "Test",
surname: "Test surname",
sizes: {
width: 200,
height: 200,
}
}
let userTwo = {
...userOne
}
userTwo.sizes.width = 50;
alert(userOne.sizes.width); // 50
So userOne and userTwo are the references the same object.
But: alert(userOne == userTwo);// false
So the the two references does not point to the same object?
Because thy are not references of the same object! They are two objects that (superficially) look the same.
Think any kind of store, you take a product from the shelf and there's a dozen identical products behind it.
Just because they look the same doesn't make them the same item.
let userTwo = userOne; creates a second reference to the same item.
let userTwo = {...userOne} creates a new object and copies the properties that are own and enumerable to that new object.
In the previous example there are two object. But what about this:
let userOne = {
name: "Test",
surname: "Test surname",
sizes: {
width: 200,
height: 200,
}
}
let userTwo = {
...userOne
}
userTwo.sizes.width = 50;
alert(userOne.sizes.width); // 50
here userOne.size === userTwo.size. so if you change one ... the other one is the same one.
but userOne !== userTwo.
You and your sibling can have the same father, and if he loses an arm, well that doesn't only apply to one of you. But that doesn't make you and your sibling the same person.
They aren't the same object.
You have two different objects, but the second one has the properties of the first copied into it with spread syntax.
It would be clearer to demonstrate if more properties were included in the second object.
let userOne = {
name: "Test",
surname: "Test"
}
let userTwo = { ...userOne,
yearOfBirth: 2000
};
console.log({
userOne
});
console.log({
userTwo
});
As you can see, the additional value is added to the second object but not the first.
The es6 spread operator {...userOne}, creates a copy of the object userOne and store it in different memory location
which is also equals to this,
let userTwo = Object.assign({}, userOne);
But if you assign the object to another,
let userThree = userOne;
This is going to return true.
This on the other hand, only compares the values
userOne.name === userTwo.name so it is returning true.
because of the logic you give in equals() method, by default they are equal.

Design pattern to check if a JavaScript object has changed

I get from the server a list of objects
[{name:'test01', age:10},{name:'test02', age:20},{name:'test03', age:30}]
I load them into html controls for the user to edit.
Then there is a button to bulk save the entire list back to the database.
Instead of sending the whole list I only want to send the subset of objects that were changed.
It can be any number of items in the array. I want to do something similar to frameworks like Angular that mark an object property like "pristine" when no change has been done to it. Then use that flag to only post to the server the items that are not "pristine", the ones that were modified.
Here is a function down below that will return an array/object of changed objects when supplied with an old array/object of objects and a new array of objects:
// intended to compare objects of identical shape; ideally static.
//
// any top-level key with a primitive value which exists in `previous` but not
// in `current` returns `undefined` while vice versa yields a diff.
//
// in general, the input type determines the output type. that is if `previous`
// and `current` are objects then an object is returned. if arrays then an array
// is returned, etc.
const getChanges = (previous, current) => {
if (isPrimitive(previous) && isPrimitive(current)) {
if (previous === current) {
return "";
}
return current;
}
if (isObject(previous) && isObject(current)) {
const diff = getChanges(Object.entries(previous), Object.entries(current));
return diff.reduce((merged, [key, value]) => {
return {
...merged,
[key]: value
}
}, {});
}
const changes = [];
if (JSON.stringify(previous) === JSON.stringify(current)) {
return changes;
}
for (let i = 0; i < current.length; i++) {
const item = current[i];
if (JSON.stringify(item) !== JSON.stringify(previous[i])) {
changes.push(item);
}
}
return changes;
};
For Example:
const arr1 = [1, 2, 3, 4]
const arr2 = [4, 4, 2, 4]
console.log(getChanges(arr1, arr2)) // [4,4,2]
const obj1 = {
foo: "bar",
baz: [
1, 2, 3
],
qux: {
hello: "world"
},
bingo: "name-o",
}
const obj2 = {
foo: "barx",
baz: [
1, 2, 3, 4
],
qux: {
hello: null
},
bingo: "name-o",
}
console.log(getChanges(obj1.foo, obj2.foo)) // barx
console.log(getChanges(obj1.bingo, obj2.bingo)) // ""
console.log(getChanges(obj1.baz, obj2.baz)) // [4]
console.log(getChanges(obj1, obj2)) // {foo:'barx',baz:[1,2,3,4],qux:{hello:null}}
const obj3 = [{ name: 'test01', age: 10 }, { name: 'test02', age: 20 }, { name: 'test03', age: 30 }]
const obj4 = [{ name: 'test01', age: 10 }, { name: 'test02', age: 20 }, { name: 'test03', age: 20 }]
console.log(getChanges(obj3, obj4)) // [{name:'test03', age:20}]
Utility functions used:
// not required for this example but aid readability of the main function
const typeOf = o => Object.prototype.toString.call(o);
const isObject = o => o !== null && !Array.isArray(o) && typeOf(o).split(" ")[1].slice(0, -1) === "Object";
const isPrimitive = o => {
switch (typeof o) {
case "object": {
return false;
}
case "function": {
return false;
}
default: {
return true;
}
}
};
You would simply have to export the full list of edited values client side, compare it with the old list, and then send the list of changes off to the server.
Hope this helps!
Here are a few ideas.
Use a framework. You spoke of Angular.
Use Proxies, though Internet Explorer has no support for it.
Instead of using classic properties, maybe use Object.defineProperty's set/get to achieve some kind of change tracking.
Use getter/setting functions to store data instead of properties: getName() and setName() for example. Though this the older way of doing what defineProperty now does.
Whenever you bind your data to your form elements, set a special property that indicates if the property has changed. Something like __hasChanged. Set to true if any property on the object changes.
The old school bruteforce way: keep your original list of data that came from the server, deep copy it into another list, bind your form controls to the new list, then when the user clicks submit, compare the objects in the original list to the objects in the new list, plucking out the changed ones as you go. Probably the easiest, but not necessarily the cleanest.
A different take on #6: Attach a special property to each object that always returns the original version of the object:
var myData = [{name: "Larry", age: 47}];
var dataWithCopyOfSelf = myData.map(function(data) {
Object.assign({}, data, { original: data });
});
// now bind your form to dataWithCopyOfSelf.
Of course, this solution assumes a few things: (1) that your objects are flat and simple since Object.assign() doesn't deep copy, (2) that your original data set will never be changed, and (3) that nothing ever touches the contents of original.
There are a multitude of solutions out there.
With ES6 we can use Proxy
to accomplish this task: intercept an Object write, and mark it as dirty.
Proxy allows to create a handler Object that can trap, manipulate, and than forward changes to the original target Object, basically allowing to reconfigure its behavior.
The trap we're going to adopt to intercept Object writes is the handler set().
At this point we can add a non-enumerable property flag like i.e: _isDirty using Object.defineProperty() to mark our Object as modified, dirty.
When using traps (in our case the handler's set()) no changes are applied nor reflected to the Objects, therefore we need to forward the argument values to the target Object using Reflect.set().
Finally, to retrieve the modified objects, filter() the Array with our proxy Objects in search of those having its own Property "_isDirty".
// From server:
const dataOrg = [
{id:1, name:'a', age:10},
{id:2, name:'b', age:20},
{id:3, name:'c', age:30}
];
// Mirror data from server to observable Proxies:
const data = dataOrg.map(ob => new Proxy(ob, {
set() {
Object.defineProperty(ob, "_isDirty", {value: true}); // Flag
return Reflect.set(...arguments); // Forward trapped args to ob
}
}));
// From now on, use proxied data. Let's change some values:
data[0].name = "Lorem";
data[0].age = 42;
data[2].age = 31;
// Collect modified data
const dataMod = data.filter(ob => ob.hasOwnProperty("_isDirty"));
// Test what we're about to send back to server:
console.log(JSON.stringify(dataMod, null, 2));
Without using .defineProperty()
If for some reason you don't feel comfortable into tapping into the original object adding extra properties as flags, you could instead populate immediately
the dataMod (array with modified Objects) with references:
const dataOrg = [
{id:1, name:'a', age:10},
{id:2, name:'b', age:20},
{id:3, name:'c', age:30}
];
// Prepare array to hold references to the modified Objects
const dataMod = [];
const data = dataOrg.map(ob => new Proxy(ob, {
set() {
if (dataMod.indexOf(ob) < 0) dataMod.push(ob); // Push reference
return Reflect.set(...arguments);
}
}));
data[0].name = "Lorem";
data[0].age = 42;
data[2].age = 31;
console.log(JSON.stringify(dataMod, null, 2));
Can I Use - Proxy (IE)
Proxy - handler.set()
Global Objects - Reflect
Reflect.set()
Object.defineProperty()
Object.hasOwnProperty()
Without having to get fancy with prototype properties you could simply store them in another array whenever your form control element detects a change
Something along the lines of:
var modified = [];
data.forEach(function(item){
var domNode = // whatever you use to match data to form control element
domNode.addEventListener('input',function(){
if(modified.indexOf(item) === -1){
modified.push(item);
}
});
});
Then send the modified array to server when it's time to save
Why not use Ember.js observable properties ? You can use the Ember.observer function to get and set changes in your data.
Ember.Object.extend({
valueObserver: Ember.observer('value', function(sender, key, value, rev) {
// Executes whenever the "value" property changes
// See the addObserver method for more information about the callback arguments
})
});
The Ember.object actually does a lot of heavy lifting for you.
Once you define your object, add an observer like so:
object.addObserver('propertyKey', targetObject, targetAction)
My idea is to sort object keys and convert object to be string to compare:
// use this function to sort keys, and save key=>value in an array
function objectSerilize(obj) {
let keys = Object.keys(obj)
let results = []
keys.sort((a, b) => a > b ? -1 : a < b ? 1 : 0)
keys.forEach(key => {
let value = obj[key]
if (typeof value === 'object') {
value = objectSerilize(value)
}
results.push({
key,
value,
})
})
return results
}
// use this function to compare
function compareObject(a, b) {
let aStr = JSON.stringify(objectSerilize(a))
let bStr = JSON.stringify(objectSerilize(b))
return aStr === bStr
}
This is what I think up.
It would be cleanest, I’d think to have the object emit an event when a property is added or removed or modified.
A simplistic implementation could involve an array with the object keys; whenever a setter or heck the constructor returns this, it first calls a static function returning a promise; resolving: map with changed values in the array: things added, things removed, or neither. So one could get(‘changed’) or so forth; returning an array.
Similarly every setter can emit an event with arguments for initial value and new value.
Assuming classes are used, you could easily have a static method in a parent generic class that can be called through its constructor and so really you could simplify most of this by passing the object either to itself, or to the parent through super(checkMeProperty).

Updating pointers within Mongoose Objects

Hi so I am working on a project using MongoDB and Mongoose.
I have a scheme where I check if a certain attribute exists for a given Mongoose object; if it doesn't I create a new one with a pointer; if there exists one I merely get a pointer to it.
Now I update the contents of these pointers, and I attempt to .save() the Mongoose object. However it does not update. I've used console logs and it tells me that the pointers have changed but not the actual contents inside the Mongoose objects. Has anyone else come by this problem? Is there any way around this? Does it matter the order I do it (as in if I push data into an attribute of the object then I modify the contents of the pointer or visa-versa)?
I also thought about how pointers get affected by pushing into arrays, but if I remember correctly java shallow copies content into arrays. So the pointers should still point to the same object?
Thanks
Model.findOne({ name: personA.name }, function(err, model) {
// if such an object exists dbModel points to it otherwise create new object
var dbModel;
if(model) dbModel = model;
else dbModel = new Model({
name: personA.name,
hobbies: []
});
var newHobby;
// helper function returns index of object in the array with sports = basketball
// if no such object exists returns -1
hobbyIdx = indexOfWithAttr(dbModel.hobbies, "sports", "basketball");
if(hobbyIdx == -1) {
newHobby = {
sports: basketball,
gears: []
}
dbModel.hobbies.push(newHobby);
}
else { newHobby = dbModels.hobbies[hobbyIdx]; }
// code changing contents of newHobby goes here...
newHobby.gears.push("sneakers");
// then finally save...
dbModel.save();
}
then the output is
//prints '{ sports: basketball }'
console.log(newHobby);
// prints '{ name: John, hobbies: [{ sports: basketball }] }'
console.log(dbModel);

how to create a hashtable of json objects in javascript?

I want to create a hashtable of json objects, where each json object represents a user.
I want to do this to sort of create a client side 'cache' of users.
User { ID: 234, name: 'john', ..);
So I can then reference things like this:
if(userCache[userid] != null)
alert(userCache[userid].ID);
is this possible?
Javascript objects themselves are maps, so for instance:
var userCache = {};
userCache['john'] = {ID: 234, name: 'john', ... };
userCache['mary'] = {ID: 567, name: 'mary', ... };
userCache['douglas'] = {ID: 42, name: 'douglas', ... };
// Usage:
var id = 'john';
var user = userCache[id];
if (user) alert(user.ID); // alerts "234"
(It wasn't clear to me whether your "userid" would be "john" or 234, so I went with "john" above, but you could use 234 if you preferred.)
It's up to the implementation how the keys are stored and whether the map is a hash map or some other structure, but I've done this with hundreds of objects and been perfectly happy with the performance, even on IE, which is one of the slower implementations (at the moment).
This works because there are two ways to get at the properties of a Javascript object: Via dotted notation, and via bracketed notation. For example:
var foo = {bar: 10};
alert(foo.bar); // alerts "10"
alert(foo['bar']); // alerts "10"
alert(foo['b' + 'a' + 'r']); // alerts "10"
s = "bar";
alert(foo[b]); // alerts "10"
It may seem strange that this bracketed syntax for getting an object property by name is the same as getting an array element by index, but in fact, array indexes are object properties in Javascript. Property names are always strings (in theory), but auto-conversion occurs when you do things like user[234]. (And implementations are free to optimize-out the conversion if they can, provided the semantics are maintained.)
Edit Some bits and pieces:
Looping through the cache
And if you want to loop through the cache (and based on your follow-up question, you do, so perhaps others reading this question will want to too):
var key, user;
for (key in userCache) {
// `key` receives the name of each property in the cache, so "john",
// "mary", "douglas"...
user = userCache[key];
alert(user.ID);
}
The keys are looped in no defined order, it varies by browser.
Deleting from the cache
Suppose you want to delete a property from the cache entirely:
delete userCache['john'];
Now there is no longer a "john" property in the object at all.
This is almost verbatim your code, but it works, yes:
var cache = {}
cache[234] = { id: 234, name: 'john' }
if (cache[1]) alert('Hello ' + cache[1].name);
if (cache[234]) alert('Hello ' + cache[234].name);
Or was your question on how to implement this on the server side too, to get the user cache to the client?
function findUser(users, userid) {
for (var i = 0; i < users.length; i++) {
if (users[i].ID === userid) {
return users[i];
}
}
return null;
}
var users = [{ ID: 234, name: 'john' }, { ID: 235, name: 'smith' }];
var user = findUser(users, 235);
if (user != null) {
alert(user.name);
}
Since all objects in Javascript are really dictionaries, you can do this in a couple ways.
One way might be:
var dict = new Object;
dict.Bobby = { ID: 1, Name: "Bobby" };
if (dict.Bobby != null) alert(dict.Bobby.Name);

Categories

Resources