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

fn-update

v1.15.0

Published

Expressive, immutable update library

Downloads

295

Readme

fn-update

Functional updates for immutable objects

Why?

Because:

const makeYourPoint = (extending) => ({
  ...extending, 
  stuff: 'can', 
  be:{
    ...stuff.be,
    really:{
      ...stuff.be.really,
      tedious:{ 
        ...stuff.be.really.tedious,
        especially:{
          ...stuff.be.really.tedious.especially,
          when: {
            deeply: 'nested!',
            'point was already made?': (
              extending.stuff.be.really.tedious.especially.when &&
              extending.stuff.be.really.tedious.especaially.when.deeply)  === 'nested!'
          }
        }
      }
    }
  }
})

Instead, how about this?

const makeYourPoint = updates({
  stuff: 'can',
  be: updateAt(['really','tedious','especially','when'], (whenObj) => ({
    deeply: 'nested!',
    'point was already made?': whenObj && whenObj.deeply === 'nested!'
  }))
})

Sweet. What else?

fn-update is cool (useful?) because:

  • updates preserve identity(!), recursively - especially useful for libraries like Redux. No unnecessary re-renders.
  • the interface is flexible - update functions are decoupled from the structure they are updating (i.e. you do not need to supply updates in the same nested structure as the object you are updating). This is especially useful for manipulating normalized json structures
  • all updates are curried functions... so you can pass them around, filter them, compose them, reuse them..
  • special treatment of delete and rename operations

Idiomatic use cases

By far the most valuable use-case for fn-update is transforming data.

For example:

  • transforming state in a Redux reducer
  • tweaking an API response in a promise chain
  • reusing or combining transformations
// some illustrative examples:

// 1. Transforming an api response with nested values
const toUpperCase = (value) => value.toUpperCase()
fetchJson('https://some-api.com/person.json')
    .then(updates({
      name: toUpperCase,
      address: updates({
        postCode: toUpperCase,
        country: 'GB',
        planet: ops.delete
      })
    }))



// 2. Updating redux state in a reducer:
// Instead of creating new objects every time, the updaters
// only modify what's necessary. This likely means fewer renders!
const reducer = (state,action) => ({

  'USER_LOADING' : (result) => updates({
    ready:false
  }),
  'USER_LOADED' : (result) => updates({
    ready: true,
    user: result
  }),
  'UPDATE_ADDRESS' : (result) => updates({
    updatesSinceLastSave: (c) => c+1,
    user: updates({
      address: result
    })
  })
  
})[action.type](action.payload)(state)

Usage

const {updateAt} = require('fn-update')

const person = {
  name:'Ben',
  preferences:{
    whisky:{
      region:'speyside'
    }
  }
}

// Basic usage: Update a deeply nested value
const shoutyBen = updateAt(['preferences','whisky','region'], v => v.toUpperCase())(person)

// Constant values are applied as if they were lifted
const ambivalentBen = updateAt(['preferences','whisky','region'], 'whatever')(person)

// Missing keys along a path are created when set
const alcoholicBen = updateAt(['preferences','brandy','region'],'yes')(person)

// Each value in the path is passed to the updater function:
const descriptiveBen = updateAt(
  ['preferences','whisky','region'],
  (region,whisky,preferences,rootObject) => {
    // We have access to each parent value as varargs
    return `${rootObject.name}'s preferential region is ${region}`
  }
)
const {updateAt,updates} = require('fn-update')

// Multiple `updateAt` calls can be composed with `updates`
const oldAndBoringBen = updates([
  updateAt('age',92),
  updateAt(['preferences','food'],'rusks'),
  updateAt(['preferences','whisky','region'],'none')
])(person)
const {updateAt,updates} = require('fn-update')

// `updates` can also take a pattern of updaters instead of a list
const oldAndBoringBen = updates({
  age: 92,
  preferences: updates({
    food: 'rusks',
    whisky: updateAt('region','none')
  })
})(person)
// You can generate update functions any way you like.

// All the functions here do the same thing:

// This function:
updates( ['colour','orange juice','toothpaste'].map(
  pref => updateAt(['preferences',pref],'all')
))

// is equivalent to:
updateAt(['preferences'], updates({
  color: 'all',
  'orange juice': 'all',
  'toothpaste': 'all'
}))

// is equivalent to:
updates({
  preferences: updates({
    'color': 'all',
    'orange juice': 'all',
    'toothpaste': 'all'
  })
})

// is (almost) equivalent to:
// ( this one always creates a new `prefs` object, whereas the others won't if prefs isn't materially changed )
updateAt(['preferences'], (prefs) => ({
  ...prefs,
  'colour': 'all',
  'orange juice': 'all',
  'toothpaste': 'all'
}))

// is equivalent to:
updates([
  updateAt(['preferences','colour'], 'all'),
  updateAt(['preferences','orange juice'], 'all'),
  updateAt(['preferences','toothpaste'], 'all'),
  false && updateAt(['preferences'],'oh-no-we-gon-lose-everything!')
].filter(Boolean))

// Keys can be renamed or deleted
const {updateAt,ops} = require('fn-update')

const namelessBen = updateAt(['name'], ops.delete)(person)

const americanBen = updateAt(['preferences','whisky'], ops.renameTo('whiskey'))(person)
// Array values can be updated too:
const confusedSuperman = { aliases: ['Clark Kent','Kal something'] }
const superman = updateAt(['aliases',1],'Kal El')(confusedSuperman)

// and deleted
const clarkKent = updateAt(['aliases',1],ops.delete)(superman)

// although you could of course do the same thing with a filter...
const alsoClarkKent = updateAt(['aliases'],aliases => aliases.filter(x => x !== 'Kal El'))(superman)
// You can ignore null/undefined values by using 'nonNil'
const makePersonOlder = updates.nonNil({
	age: (age) => age + 10
})

const stillUndefined = makePersonOlder(undefined)
const sillNull = makePersonOlder(null)