Object#reverseMerge – Useful JavaScript Game Extensions #19

Object#reverseMerge a method that complements Object#merge nicely. In regular merge all the properties of the source are copied onto the destination, but in reverseMerge the properties are only copied over if the destination doesn’t already have the property.

Object.prototype.reverseMerge = function(source) {
  for(var key in source) {
    if(source.hasOwnProperty(key) && !(key in this)) {
      this[key] = source[key];
    }
  }
 
  return this;
};

This allows us to easily have a list of default properties in an object and add them to the destination object only if they aren’t already present.

var iceCreamDefaults = {
  flavor: "vanilla",
  price: 2,
  size: 4
};
 
 
var chocolate = {
  flavor: "chocolate"
}.reverseMerge(iceCreamDefaults);
 
chocolate.price; // 2
chocolate.size; // 4

In the example we have an object containing ice cream default values. These values are merged into the chocolate object we create, but only if they don’t already exist within that object.

Extending Object.prototype is fun and rewarding, but it’s not without it’s pitfalls. For example jQuery is not yet 100% compatible with code that extends Object.prototype, though it has plans to be in the future. In addition, the presence of prototype properties in all your objects is one extra edge case to consider when using for in iteration and the in operator. The primary question is whether the benefit added by Object.prototype extensions exceeds the risk of the extra complexity, and in the end it comes down to what the biggest pain points are in the code in your own specific circumstances. Like most programming practices that involve trade-offs their correct usage depends strongly on the context where they are used.

Be sure to subscribe to get all the latest updates!

Bonus section, an alternate implementation using Object#each:

Object.prototype.reverseMerge = function(source) {
  source.each(function(key, value) {
    if(!(key in this)) {
      this[key] = value;
    }
  }, this); // context argument to ensure that `this` references correctly
 
  return this;
};

Again, be sure to subscribe so you don’t miss any of this amazing series!

2 thoughts on “Object#reverseMerge – Useful JavaScript Game Extensions #19


  1. jared:

    Hey I’m loving this series. Its really good stuff. Plus the Pixie ide is awesome.

    Thanks for the feedback! The IDE is still under heavy development, let me know what features, documentation, or tutorials would be most helpful and I’ll try to work them in.

Leave a Reply

Your email address will not be published. Required fields are marked *