Created
March 17, 2016 19:01
-
-
Save thurt/bc81da3c7c696e42afc9 to your computer and use it in GitHub Desktop.
This file contains 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
// approximate implementation of Set using Symbol (ES6) | |
(() => { | |
function aSet() { | |
this.hash = {} | |
} | |
aSet.prototype = { | |
add(a) { this.hash[a] = true }, | |
has(a) { return a in this.hash }, | |
values() { return Object.keys(this.hash) }, | |
delete(a) { delete this.hash[a] }, | |
clear() { this.hash = {} } | |
} | |
var mySet = new aSet() | |
var myObj = Object(Symbol('myObj')) | |
myObj.a = 1 | |
myObj.b = 2 | |
mySet.add(myObj) | |
console.log(mySet.has(myObj)) // true | |
})() | |
// approximate implementation of Set without Symbol | |
// ES5 compatible | |
// - create unique hash keys | |
// - local override #toString | |
(() => { | |
function aSet() { | |
this.hash = {} | |
} | |
aSet.prototype = { | |
add: function(a) { this.hash[a] = true }, | |
has: function(a) { return a in this.hash }, | |
values: function() { return Object.keys(this.hash) }, | |
delete: function(a) { delete this.hash[a] }, | |
clear: function() { this.hash = {} } | |
} | |
var count = 0 | |
function id(i) { | |
count++ | |
return function() { | |
return String(i) | |
} | |
} | |
var mySet = new aSet() | |
var myObj = { a: 1, b: 2, toString: id(count) } | |
mySet.add(myObj) | |
console.log(mySet.has(myObj)) // true | |
})() | |
// same as above with a less fragile SetObject abstraction | |
(() => { | |
function aSet() { | |
this.hash = {} | |
} | |
aSet.prototype = { | |
add: function(a) { this.hash[a] = true }, | |
has: function(a) { return a in this.hash }, | |
values: function() { return Object.keys(this.hash) }, | |
delete: function(a) { delete this.hash[a] }, | |
clear: function() { this.hash = {} } | |
} | |
var SetObject = (function() { | |
var count = 0 | |
return function(obj) { | |
Object.defineProperty(obj, 'toString', { | |
value: (function(i) { | |
return function() { | |
return '__SetObject__' + i | |
} | |
})(count), | |
enumerable: false | |
}) | |
count++ | |
return obj | |
} | |
})() | |
var mySet = new aSet() | |
var mySetObj = SetObject({ a: 1, b: 2 }) | |
mySet.add(mySetObj) | |
console.log(mySet.has(mySetObj)) // true | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compare SetObject to Data Warehouse: https://gist.github.com/thurt/c654dd88e3981f410d50