Socket
Socket
Sign inDemoInstall

generic-diff

Package Overview
Dependencies
1
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    generic-diff

Diff any array-like object, including strings


Version published
Weekly downloads
326
increased by68.04%
Maintainers
1
Install size
14.0 kB
Created
Weekly downloads
 

Readme

Source

generic-diff

Diff arrays or array-like objects, such as strings. Based on "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).

diff( a, b [, eql] )

Diffs the array-like objects a and b, returning a summary of edits required to turn a into b. Defaults to using strict equality (===) to compare items in a and b. A comparison function, eql, can optionally be used for more nuanced comparisons; the signature of this function is (item from a, item from b) => Boolean.

The “summary of changes” is an array of objects with three properties: items, an array of one or more items from a or b, and boolean properties added and removed, indicating whether the item(s) should be added or removed from a, respectively. For example, if we’re diffing the strings abc and abd, the summary of changes would look like:

[{
  items: ['a', 'b'],
  added: false,
  removed: false
}, {
  items: ['c'],
  added: false,
  removed: true
}, {
  items: ['d'],
  added: true,
  removed: false
}]

Example

Diff two strings, creating an HTML representation of their differences:

var diff = require('generic-diff')

var changes = diff('falafel', 'fallacy')
changes = changes.map(function (edit) {
  if (edit.added) {
    return '<ins>' + edit.items.join('') + '</ins>'
  } else if (edit.removed) {
    return '<del>' + edit.items.join('') + '</del>'
  } else {
    return edit.items.join('')
  }
}).join('')

console.log(changes)
// 'fal<del>afe</del>l<ins>acy</ins>'

For a slightly more involved example, this gist demonstrates how to diff two files and produce an output similar to the UNIX diff command.

LICENSE

MIT

Keywords

FAQs

Last updated on 20 Dec 2015

Did you know?

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

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc