Skip to content

Instantly share code, notes, and snippets.

@Gwash3189
Created July 20, 2014 07:05
Show Gist options
  • Save Gwash3189/dd8f9ce9bf7f94ed8028 to your computer and use it in GitHub Desktop.
Save Gwash3189/dd8f9ce9bf7f94ed8028 to your computer and use it in GitHub Desktop.
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Immutable = (function () {
function Immutable() {
this.objectString = "object";
}
Immutable.prototype.Freeze = function () {
Object.freeze(this);
return this;
};
Immutable.prototype.copy = function (obj) {
var copy;
var toCopy = obj || toCopy;
if (toCopy instanceof Array) {
copy = [];
} else {
copy = {};
}
var keys = Object.keys(toCopy);
for (var i = 0; i < keys.length; i++) {
if (typeof toCopy[keys[i]] !== this.objectString) {
copy[keys[i]] = toCopy[keys[i]];
} else {
copy[keys[i]] = this.copy(toCopy[keys[i]]);
}
}
return copy;
};
Immutable.prototype.Copy = function (obj) {
return this.copy(obj || this);
;
};
return Immutable;
})();
interface IImmuatable {
Freeze: () => IImmuatable;
Copy: <T>(obj: any) => T;
}
class Immutable implements IImmuatable{
private objectString = "object";
public Freeze () {
Object.freeze(this);
return this;
}
private copy(obj? : IImmuatable) {
var copy;
var toCopy = obj || toCopy;
if(toCopy instanceof Array){
copy = [];
} else {
copy = {};
}
var keys = Object.keys(toCopy);
for(var i = 0; i < keys.length; i++){
if(typeof toCopy[keys[i]] !== this.objectString){
copy[keys[i]] = toCopy[keys[i]];
} else {
copy[keys[i]] = this.copy(toCopy[keys[i]]);
}
}
return copy;
}
public Copy<T> (obj?: Immutable): T {
return <T>this.copy(obj || this);;
}
}
var Person = (function (_super) {
__extends(Person, _super);
function Person(Name) {
_super.call(this);
this.Name = Name;
}
return Person;
})(Immutable);
var p = new Person("Adam");
p.Freeze();
console.assert(p.Name === "Adam");
p.Name = "Derp";
console.assert(p.Name === "Adam");
var q = p.Copy<Person>(); //Create a copy of the Object , the copy should not be frozen.
console.assert(q.Name === "Adam"); //should keep it's old values.
q.Name = "Derp"; // should now be another value, despite having Freeze called on it's source.
console.log(q.Name === "Derp");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment