Skip to content

kapouer/levenlistdiff

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

levenlistdiff

Fork of list-diff.js, with support for a hash function.

Introduction

Diff two lists/strings in time O(n*m).

The algorithm finding the minimal amount of moves(patches) is Levenshtein distance.

Install

npm install levenlistdiff --save

Usage

var Diff = require("levenlistdiff")
var oldList = [{id: "a"}, {id: "b"}, {id: "c"}, {id: "d"}, {id: "e"}]
var newList = [{id: "c"}, {id: "a"}, {id: "b"}, {id: "e"}, {id: "f"}]

var patches = Diff(oldList, newList, "id")

patches.forEach(function (patch) {
  if (patch.type === Diff.DELETION) {
    oldList.splice(patch.index, 1)
  } else if (patch.type === Diff.INSERTION) {
    oldList.splice(patch.index, 0, patch.item)
  } else if (patch.type === Diff.SUBSTITUTION) {
    oldList.splice(patch.index, 1, patch.item)
  }
})

// now `oldList` is equal to `newList`
// [{id: "c"}, {id: "a"}, {id: "b"}, {id: "e"}, {id: "f"}]
console.log(oldList)

With a custom hash function:

var patches = Diff(oldList, newList, function(item) {
	return item.id
})

If levenlistdiff.js is added to a web page, it is exposed as window.ListDiff.

License

MIT

About

Diff two lists/strings in O(n*m)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%