Last active
August 29, 2015 14:01
-
-
Save dschenkelman/99e0453d58cea7e02d62 to your computer and use it in GitHub Desktop.
Frozen Proxies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var immutable = (function(){ | |
function isFunction(f) { | |
var getType = {}; | |
return f && getType.toString.call(f) === '[object Function]'; | |
} | |
function shallowCopy(object){ | |
var copy = Object.create(Object.getPrototypeOf(object)); | |
Object.getOwnPropertyNames(object).forEach(function (name){ | |
copy[name] = object[name]; | |
}); | |
return copy; | |
} | |
return function immutable(object){ | |
var proxy = new Proxy(object, { | |
get: function(target, originalName){ | |
if (originalName.indexOf('with') === 0 && originalName.length > 4) | |
{ | |
var capitalizedName = originalName.substring(4); | |
var name = capitalizedName.charAt(0).toLowerCase() + capitalizedName.slice(1); | |
var attribute = target[name]; | |
if (!attribute || !isFunction(attribute)){ | |
return function(value){ | |
var copy = shallowCopy(object); | |
copy[name] = value; | |
return immutable(copy); | |
}; | |
} | |
} | |
return target[originalName]; | |
} | |
}); | |
Object.freeze(object); | |
return proxy; | |
}; | |
})(); | |
function Vehicle(hasEngine, hasWheels) { | |
this.hasEngine = hasEngine || false; | |
this.hasWheels = hasWheels || false; | |
}; | |
function Car (make, model, hp) { | |
this.hp = hp; | |
this.make = make; | |
this.model = model; | |
}; | |
Car.prototype = new Vehicle(true, true); | |
var car = immutable(new Car('Hyundai', 'Elantra', 10)); | |
console.log(car.hp); | |
console.log(car.make); | |
console.log(car.model); | |
console.log(car.hasEngine); | |
console.log(car.hasWheels); | |
console.log(car.hasMirrors); | |
var car2 = car.withHp(car.hp + 20).withHasMirrors(true); | |
console.log(car2.hp); | |
console.log(car2.make); | |
console.log(car2.model); | |
console.log(car2.hasEngine); | |
console.log(car2.hasWheels); | |
console.log(car2.hasMirrors); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment