Blog
`fast-deep-equal` package in Puck codebase.

`fast-deep-equal` package in Puck codebase.

In this article, we review fast-deep-equal package in Puck codebase. We will look at:

  1. What is fast-deep-equal package?

  2. Usage in Puck codebase.

What is fast-deep-equal package?

fast-deep-equal package the fastest deep equality check with Date, RegExp and ES6 Map, Set and typed arrays support.

Install

npm install fast-deep-equal

Features

  • ES5 compatible

  • works in node.js (8+) and browsers (IE9+)

  • checks equality of Date and RegExp objects by value.

ES6 equal (require('fast-deep-equal/es6')) also supports:

  • Maps

  • Sets

  • Typed arrays

Usage

var equal = require('fast-deep-equal');
console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true

To support ES6 Maps, Sets and Typed arrays equality use:

var equal = require('fast-deep-equal/es6');
console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true

To use with React (avoiding the traversal of React elements’ _owner property that contains circular references and is not needed when comparing the elements — borrowed from react-fast-compare):

var equal = require('fast-deep-equal/react');
var equal = require('fast-deep-equal/es6/react');

Learn more about fast-deep-equal.

Usage in Puck codebase.

In puck/packages/core/lib/get-changed.ts, you will find the following code:

import { ComponentData } from "../types";
import fdeq from "fast-deep-equal";

export const getChanged = (
  newItem: Omit<Partial<ComponentData<any>>, "type"> | undefined,
  oldItem: Omit<Partial<ComponentData<any>>, "type"> | null | undefined
) => {
  return newItem
    ? Object.keys(newItem.props || {}).reduce((acc, item) => {
        const newItemProps = newItem?.props || {};
        const oldItemProps = oldItem?.props || {};

        return {
          ...acc,
          [item]: !fdeq(oldItemProps[item], newItemProps[item]),
        };
      }, {})
    : {};
};

This code tells us that you could import something like fdeq from the fast-deep-equal.

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Want to learn from open-source? Solve challenges inspired by open-source projects.

References:

  1. https://github.com/puckeditor/puck/blob/main/packages/core/lib/get-changed.ts

  2. https://www.npmjs.com/package/fast-deep-equal

  3. https://github.com/epoberezkin/fast-deep-equal