Skip to content

Instantly share code, notes, and snippets.

@dtipson
Created April 24, 2017 20:58
Show Gist options
  • Select an option

  • Save dtipson/41e3ba52878be74fcc79cff48d6ab0da to your computer and use it in GitHub Desktop.

Select an option

Save dtipson/41e3ba52878be74fcc79cff48d6ab0da to your computer and use it in GitHub Desktop.

Revisions

  1. dtipson created this gist Apr 24, 2017.
    58 changes: 58 additions & 0 deletions KeyedCollection.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    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...
    }
    }