@scandinavia/deep-merge
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

@scandinavia/deep-merge

deeply merge list of objects.

Usage

lets say you have two optional properties (variant, onClick), when he passed variant you want to override the default variant, and when he pass onClick event handler you want to fire it side by side with your event.

import { deepMerge } from '@scandinavia/deep-merge';

type MyFancyButtonProps = {
  variant?: 'filled' | 'outlined';
  onClick?: () => void;
};

/* Old Way 🤕
 * you have to keep in mind the various properties
 * and how they should react if the same property came from
 * the end-developer.
 */
const MyFancyButton: React.FC<MyFancyButtonProps> = props => {
  return (
    <button
      variant='filled'
      {...props}
      onClick={() => {
        console.log('`MyFancyButton` Clicked!');
        props?.onClick?.();
      }}
    />
  );
};

/* With `deep-merge` 😍
 * it's just merging two objects and return the result
 * no matter how the end-developer provide it.
 */

const MyFancyButton: React.FC<MyFancyButtonProps> = props => {
  return (
    <button
      {...deepMerge(
        {
          variant: 'filled',
          onClick: () => console.log('`MyFancyButton` Clicked!'),
        },
        props
      )}
    />
  );
};

if you don't want to merge the functions (just override the function) you can import createDeepMerge and pass options to it.

import { createDeepMerge } from '@scandinavia/deep-merge';
const myDeepMerge = createDeepMerge({ overrideFunctions: true });

// use `myDeepMerge` in your code.

Powerful Typing

const result = deepMerge({ a: 'str' }, { a: 1, b: 'str' });
//      '------> type of { a:string | number, b?:string | undefined }

Package Sidebar

Install

npm i @scandinavia/deep-merge

Weekly Downloads

8

Version

0.0.4

License

MIT

Unpacked Size

8.02 kB

Total Files

11

Last publish

Collaborators

  • yaman.lakis.scandinaviatech
  • ouis001
  • rami-k-youssef
  • abdulrahman-falyoun
  • scandinavia_tech
  • abd-ulhameed-maree