Skip to content

Instantly share code, notes, and snippets.

@thurt
Created March 17, 2016 19:01
// 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
})()
@thurt
Copy link
Author

thurt commented Mar 17, 2016

Compare SetObject to Data Warehouse: https://gist.github.com/thurt/c654dd88e3981f410d50

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