AlexGalays/immupdate

Would you consider a wrapper/helper?

fiatjaf opened this issue · 2 comments

Maybe an external helper could be bundled with this library, but imported separatedly:

const state = require('immupdate/state')({initial: 76})

state.get() // {initial: 76}
state.update({fruit: 'banana', initial: 84})
state.get('fruit') // 'banana'
state.get() // {initial: 84, fruit: 'banana'}

I've done something like that and was thinking about publishing it as a standalone package depending on immupdate, but perhaps it is better to bundle it here, somewhat like h in bundled into virtual-dom, if more people find this pattern useful.

Here's a first draft (full code):

import immupdate from 'immupdate'

class State {
  constructor (values) {
    this._values = values
  }

  get (key) {
    return key ? this._values[key] : this._values
  }

  set (key, value) {
    this._values = immupdate.updateKey(this._values, key, value)
  }

  update (values) {
    this._values = immupdate.update(this._values, values)
  }
}

module.exports = State

Hello, this looks interesting; however I don't see much value in including it in the main repo.
There are both pros and cons to wrapping native objects and I would prefer if developers made that choice for their project.

By the way, with the following function:

function read(obj, path) {
  return path.split('.').reduce((acc, val) => {
    if (!acc) return undefined;
    else return acc[val];
  }, obj);
}

You would be able to read nested values in get in addition to writing them with set; Worth considering.