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

@macklinu/matches

v1.0.0

Published

Simplify deep object comparisons

Downloads

9

Readme

@macklinu/matches

Simplify deep object comparisons

code style: prettier Build Status

Motivation

When writing ESLint plugins, there are a lot of deep object checking functions like this:

function isPromiseFunctionNode(node) {
  if (node.type !== 'CallExpression') {
    return false
  }
  if (node.callee.type !== 'MemberExpression') {
    return false
  }
  let propertyName = node.callee.property.name
  return propertyName === 'then' || propertyName === 'catch'
}

let nodeFromAst = {
  type: 'CallExpression',
  callee: {
    type: 'MemberExpression',
    property: {
      name: 'then',
    },
  },
}

isPromiseFunctionNode(nodeFromAst) // => true

Sometimes object properties are not present, or their values are undefined, and you are forced to write overly defensive code as a result.

Instead, my dream is to write safe, nested object checks using a schema-like syntax:

import matches from '@macklinu/matches'

let isPromiseFunctionNode = matches({
  type: 'CallExpression',
  'callee.type': 'MemberExpression',
  'callee.property.name': /then|catch/,
})

let nodeFromAst = {
  type: 'CallExpression',
  callee: {
    type: 'MemberExpression',
    property: {
      name: 'then',
    },
  },
}

isPromiseFunctionNode(nodeFromAst) // => true

Using this library, I can write the same check in a safe, declarative way while leveraging the power of regular expressions and predicate functions.

If you're curious to learn more, please read on and give this library a try! 🙂

Installation

$ yarn add @macklinu/matches

Then import the function into your codebase:

import matches from '@macklinu/matches'

// or

const matches = require('@macklinu/matches')

API

matches(predicateObject)

Returns a function that returns a boolean.

The predicateObject type is the following:

type PredicateObject = {
  [pathToKey: string]: Regexp | (value: any) => boolean | any
}

predicateObject keys are strings (the dot-separated path to a value within an object). The corresponding values can be any of the following:

  • a regular expression
let isDog = matches({
  breed: /shepherd|poodle|beagle/,
})

isDog({ breed: 'poodle' }) // => true
  • a predicate function: (value: any) => boolean
let isLeapYear = matches({
  date: value => moment(value).isLeapYear(),
})

isLeapYear({ date: '2000-01-01' }) // => true
  • any literal value (uses === equality checking)
let isHuman = matches({
  type: 'human',
})

isHuman({ type: 'human' }) // => true
isHuman({ type: 'animal' }) // => false

The predicateObject parameter must be flat, meaning it can only have one level of key-values. You can access nested objects by using dot notation like so:

let isJohnDoe = matches({
  'name.first': 'John',
  'name.last': 'Doe',
})

isJohnDoe({ name: { first: 'John', last: 'Doe' } }) // => true

This also allows you to access and check values within an array:

let isNewPromiseCallback = matches({
  type: 'ArrowFunctionExpression',
  'callee.name': 'Promise',
  'params.0.name': 'resolve',
  'params.1.name': 'reject',
})

isNewPromiseCallback({
  type: 'ArrowFunctionExpression',
  callee: { type: 'Identifier', name: 'Promise' },
  params: [
    { type: 'Identifier', name: 'resolve' },
    { type: 'Identifier', name: 'reject' },
  ],
}) // => true

Tradeoffs

  • ✅ May improve clarity as an alternative to writing many if statements in a function
  • ❌ Slower execution than a plain old function
  • 🤷‍♂️ Still can execute millions of times per second per the benchmark, so probably not a big deal unless you really need blazing speeds

Development

yarn

Installs dependencies

yarn test

Runs Jest tests and ESLint on source files. Run yarn watch --test during development for Jest's watch mode.

yarn build

Compiles the code with Babel and outputs to dist/ for publishing to npm.

yarn bench

Runs benchmarks to show that, while this is a cool idea, my implementation is magnitudes slower than just writing code like a normal human being.

Contributing

Feature requests, documentation updates, and questions are more than welcome in an issue. I'm not sure what other features or changes I'd like to make to this library at the moment but am happy to discuss. 🙂