Socket
Book a DemoInstallSign in
Socket

array-diff-items

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

array-diff-items

Detect differences between two arrays.

0.1.1
latest
Source
npmnpm
Version published
Weekly downloads
1
Maintainers
1
Weekly downloads
 
Created
Source

array-diff-items

A JavaScript module that finds the most ideal path to change an array to another array.

Demo

https://array-diff-items-example.netlify.com/

Motivations

Most diff detecting library detects "Added", "Removed", "Unchanged" operations.

['Orange', 'Apple',  'Banana']
['Grape',  'Apples', 'Banana']

=>

Removed: Orange
Removed: Apple
Added: Grape
Added: Apples
Unchanged: Banana

This kind of diff might be sufficient in many cases, but sometimes we want to detect "Change" rather than "Remove" then "Add".

['Orange', 'Apple',  'Banana']
['Grape',  'Apples', 'Banana']

=>

Removed: Orange
Added: Grape
Changed: Apple => Apples
Removed: Banana
Added: Melon

array-diff-items solves this problem by introducing "cost" to change. It prefers "Change" when its cost to change a to b is less than simply removing a and adding b.

Installation

yarn add array-diff-items

Getting Started

import arrayDiffItems from 'array-diff-items';

// type Compare<T> = (left: T, right: T) => number;
// arrayDiffElements: <T>(left: T[], right: T[]) => (compare: Compare<T>) => DiffItem<T>[];
const left  = ['Banana', 'Apple', 'Orange',          'Grape'];
const right = [          'Apple', 'Orange', 'Melon', 'Grape Fruit'];

arrayDiffItems(left, right)((a, b) => {
  // Return the cost to change "a" to "b".
  // When cost is less than 1, that means changing "a" to "b" is preferable to removing "a" and then adding "a".
  if (a === b) return 0;
  if (a.startsWith(b) || b.startsWith(a)) return 0.5;
  return 2;
});
// [
//   {"type":"Removed","item":"Banana"},
//   {"type":"Unchanged","item":"Apple"},
//   {"type":"Unchanged","item":"Orange"},
//   {"type":"Added","item":"Melon"},
//   {"type":"Changed","left":"Grape","right":"Grape Fruit"}
// ]

FAQs

Package last updated on 18 Nov 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.