npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mergerino

v0.4.0

Published

immutable state merge util

Downloads

2,614

Readme

Mergerino npm size

An immutable merge util for state management.

Mergerino works very well with the meiosis state management pattern and is offered as a setup option.

Click here to see available builds of mergerino on npm.

ESM installation

import merge from 'https://unpkg.com/mergerino?module'

const state = {
  user: {
    name: 'John',
    weight: 180,
    age: 34,
    height: 177
  },
  other: {
    many: true,
    properties: true
  }
}
const newState = merge(state, {
  user: {
    name: 'Bob',
    weight: undefined,
    age: age => age / 2
  },
  other: () => ({ replaced: true })
})

/*
result = {
  user: {
    name: 'Bob',
    age: 17,
    height: 177
  },
  other: {
    replaced: true
  }
}
*/

playground

  • state is left intact
  • each part of state that your patch instruction touched will be shallow copied into newState
  • untouched properties retain the same references.

ES5 browser installation

<script src="https://unpkg.com/mergerino"></script>
<script>
  const state = {
    user: {
      name: 'John',
      weight: 180,
      age: 34,
      height: 177
    },
    other: {
      many: true,
      properties: true
    }
  }
  const newState = mergerino(state, {
    user: {
      name: 'Bob',
      weight: undefined,
      age: function(age) {
        return age / 2
      }
    },
    other: function() {
      return { replaced: true }
    }
  })

  /*
  result = {
    user: {
      name: 'Bob',
      age: 17,
      height: 177
    },
    other: {
      replaced: true
    }
  }
  */
</script>

playground

Usage Guide

Mergerino is made up of a single function merge(target, ...patches).

Patches in mergerino are expressed as plain JavaScript objects:

merge(state, { I: { am: { just: { an: 'object' } } } })

Mergerino merges immutably meaning that the target object will never be mutated (changed). Instead each object along the path your patch specifies will be shallow copied into a new object.

The advantage of this is that patch operations are relatively quick because they only copy the parts of the object that are touched.

This means you can use strict equality (===) to determine where an object was changed by a patch operation:

const state = { obj: {} }
const newState = merge(state, { newProp: true })
console.log(state === newState) // false
console.log(state.obj === newState.obj) // true

If you want to fully remove a property from an object specify undefined as the value.

const state = { deleteMe: true }
const newState = merge(state, { deleteMe: undefined })
console.log(state) // { deleteMe: true }
console.log(newState) // {}

Use null instead of undefined if you don't want the key to be deleted.

If you want to replace a property based on its current value, use a function.

const state = { age: 10, obj: { foo: 'bar' } }
const newState = merge(state, { age: x => x * 2, obj: () => ({ replaced: true }) })
console.log(state) // { age: 10, obj: { foo: 'bar' } }
console.log(newState) // { age: 20, obj: { replaced: true } }

If you pass a function it will receive the current value as the first argument and the merge function as the second. The return value will be the replacement. The value you return will bypass merging logic and simply overwrite the property. This is useful when you want to replace an object without merging. If you would like to merge from within a function patch then use the merge function provided as the second argument.

Multiple Patches

You can pass multiple patches in a single merge call, array arguments will be flattened before processing.

All the following are valid:

merge(state, [{}, {}, {}])
merge(state, {}, {}, {})
merge(state, [[[[{}]]]])
merge(state, [{}], [{}], [{}])

Another nice side effect of flattening array arguments is that you can easily add conditions to your patches using nested arrays:

merge(state, [
  { week: 56 },
  state.age < 10 && { child: true },
  state.job === 'programmer' && [
    state.promote && { promoted: true },
    !state.salaryPaid && { schedulePayment: true }
  ]
])

If all the above conditions are false (except the job check) the final patch array before flattening will look like this:

patches === [{ week: 56 }, false, [false, false]]

Since falsy patches are ignored only { week: 56 } will be merged.

Another option is to use the spread operator to combine multiple patches into one, but it's harder/messier to write conditions using this technique as you can see:

merge(state, {
  { week: 56 },
  ...(state.age < 10 ? { child: true } : {}),
  ...(state.job === 'programmer'
    ? {
        ...(state.promote ? { promoted: true } : {}),
        ...(!state.salaryPaid ? { schedulePayment: true } : {})
      }
    : {})
})

As a reducer

Mergerino can be used as a reducer where patches are fed into a function which is then applied to a central state object. In these cases you may not have a reference to the full state object to base your patch on.

In order to help in this scenario mergerino supports passing a function as a top level patch. This function acts exactly the same as a function passed to a specific property. It receives the full state object as the first argument, the merge function as the second.

// state-manager.js
let state = { count: 10 }
const update = patch => (state = merge(state, patch))

// other.js
update({ newProp: true })
// want to use value of count to patch
update((state, m) => m(state, { double: state.count * 2 }))

// back in state-manager.js
console.log(state) // { count: 10, newProp: true, double: 20 }

// if you don't use the merge function the top level object will be replaced
update(state => ({}))
console.log(state) // {}

Credits

Check out patchinko by Barney Carroll. It was a huge inspiration for mergerino.

It takes a much more explicit approach to signaling patch operations and has some interesting API options.