Created
April 24, 2017 20:58
-
-
Save dtipson/41e3ba52878be74fcc79cff48d6ab0da to your computer and use it in GitHub Desktop.
Experimenting with a type that contains objects that are listed in insertion order but are also unique by a single chosen prop
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
const getProp = prop => object => object[prop] | |
function KeyedCollection (Iterable, prop){ | |
if (!(this instanceof KeyedCollection)) { | |
return new KeyedCollection(Iterable, prop); | |
} | |
if(!prop){ | |
throw new Error('must supply a prop') | |
} | |
const it_target = [] | |
const selectPropFrom = getProp(prop) | |
//Functor.map(obj=>[getProp(prop)(obj),obj]) | |
for (item of Iterable){ | |
it_target.push([String(selectPropFrom(item)),item]) | |
} | |
this.selectPropFrom = selectPropFrom | |
this.prop = prop; | |
this.map = new Map( | |
it_target | |
) | |
} | |
KeyedCollection.prototype.get = function(key){ | |
return this.map.get(String(key))//mutates! | |
} | |
KeyedCollection.prototype.has = function(key){ | |
return this.map.has(String(key)) | |
} | |
KeyedCollection.prototype.size = function(){ | |
return this.map.size() | |
} | |
KeyedCollection.prototype.clear = function(){ | |
return this.map.clear() | |
} | |
KeyedCollection.prototype.delete = function(key){ | |
return this.map.delete(key)//mutates! | |
} | |
KeyedCollection.prototype[Symbol.iterator] = function* (){ | |
for (let [k,v] of this.map){ | |
yield v | |
} | |
} | |
KeyedCollection.prototype.addFromArray = function(ArrayOfObjects){ | |
for (obj of ArrayOfObjects){ | |
this.map.set(this.selectPropFrom(obj),obj) | |
} | |
return this; | |
} | |
//another attempt to save an iteration.... [...KeyedCollection.toReact(Component)] | |
KeyedCollection.prototype.toReact = function *(Component){ | |
for (let [key,v] of this.map){ | |
yield Component(Object.assign(v,{key}))//is key getting assigned in the React way here? | |
//have to actually try this out... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment