Skip to content

MergeChain

James edited this page Jun 24, 2017 · 3 revisions

▶️◀️⛓ MergeChain

deeply merge all data values on a chain with ease

definition:

type Mergeable = Obj | Arr

export interface DopeMergeOptions {
  arrayMerge?: Fn
  stringToArray?: boolean = true
  boolToArray?: boolean = false
  ignoreTypes?: string[] = ['null', 'undefined', 'NaN']
  debug?: boolean = undefined
}

function dopemerge(obj1: Mergeable, obj2: Mergeable, opts?: DopeMergeOptions): Mergeable

class MergeChain extends ChainedMapBase {
  public onValue(fn?: Fn): MergeChain
  public onExisting(fn?: Fn): MergeChain
  public obj(obj: Obj): MergeChain
  public merge(objToMerge: Obj): MergeChain
}

from

  • a simplified, optimized .merge which works similar, but does not deeply merge objects unless the properties are chainable instances
  • by default, overrides existing values or sets them initially
  • mainly used for hydrating or transferring (for example, to-from localStorage, to-from webworker)

📘 examples

👾 minimal

const chain = new ChainedMap()
chain.merge({ehOh: true}) // same as chain.set('ehOh', true)
chain.entries() === {ehOh: true}

🍉 persist and hydrate

const Chain = require('chain-able')

class Canada extends Chain {
  static init(parent) { return new Canada(parent) }
  constructor(parent) {
    super('parent')
    this.extend(['eh'])
  }
}

const ls = {
  get(key) { return JSON.parse(window.localStorage.getItem(key)) },
  set(key, value) { window.localStorage.setItem(key, JSON.stringify(value)) }
}

const canada = Canada.init()
  .eh('eh!')
  .merge({canada: true})
  .tap('canada', value => '🇨🇦')
  .setIfEmpty('ooo', 'ahh')

ls.set('canada', canada)
const hydrated = new Canada().from(ls.get('canada'))

process

  • in ChainedSet arg is an Iteratable (e.g. Array)
  • in ChainedMap arg is an Object
  • iterate over the object keys:
    • if there an instance property matching the key
      • if it's a chainable instance (e.g. this.list = new ChainedSet(this))
        • call .merge on the instance
      • else if it's a method
        • if the method is in .shorthands (added for every .extend)
        • if the value is in the store, tap the value & deeply merge the value with the existing one
        • call the method with the value
    • default/fallback
      • if existing value, deeply value- merge
      • .set

🔗 related