Skip to content

Instantly share code, notes, and snippets.

@keithwhor
Created July 21, 2015 16:55
Show Gist options
  • Save keithwhor/cd3784529b70f9627097 to your computer and use it in GitHub Desktop.
Save keithwhor/cd3784529b70f9627097 to your computer and use it in GitHub Desktop.
Basic Unit class for graphs
class Unit {
// Entity is used as node or edge type, for different classifications
// i.e. 'person', 'game', 'road', etc.
constructor(entity, properties) {
this.entity = entity + '';
this.load(properties || {});
}
// load properties (id, name, age, etc.) from an object
load(properties) {
let p = Object.create(null);
Object.keys(properties).forEach(function(v) {
p[v] = properties[v];
});
this.properties = p;
return this;
}
set(property, value) {
return this.properties[property] = value;
}
unset(property) {
return delete this.properties[property];
}
has(property) {
return Object.prototype.hasOwnProperty.call(this.properties, property);
}
get(property) {
return this.properties[property];
}
toString() {
return [this.constructor.name, ' (', this.entity, ' ', JSON.stringify(this.properties) ,')'].join('');
}
}
@mdibaiee
Copy link

Okay, now I see you're using Object.create(null), what's the advantage of using this instead of creating an object with Object as it's prototype? Is there some real-life example of how it would be useful? Is it some kind of optimization? Thanks!

(Couldn't edit my last comment, getting an empty error)

@mdibaiee
Copy link

Also, as long you're not inheriting anything, any property is actually an own property, so why not use the in operator:

  return (property in this.properties);

@mfuentesg
Copy link

You can use the default value in parameter

14| load(properties = {})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment