GithubHelp home page GithubHelp logo

list-diff's Introduction

list-diff

时间复杂度是O(n)的两个列表diff算法

使用

	var diff = require("list-diff");
	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 moves = diff(oldList, newList, "id");
	// `moves` is a sequence of actions (remove or insert): 
	// type 0 is removing, type 1 is inserting
	// moves: [
	//   {index: 3, type: "delete"},
	//   {index: 0, type: "insert", item: {id: "c"}}, 
	//   {index: 0, type: "delete"}, 
	//   {index: 4, type: "insert", item: {id: "f"}}
	//  ]

	moves.forEach(function(move) {
	  	if (move.type === 'delete') {
	    	oldList.splice(move.index, 1); // type 0 is removing
	  	} else {
	    	oldList.splice(move.index, 0, move.item); // type 1 is inserting
	  	}
	});

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

说明

两个list列表的diff实现,这是一个。还有一种是最小编辑距离实现,是基于动态规划的,有兴趣的可以自己研究下。

list-diff's People

Contributors

abell123456 avatar

Stargazers

ruixing avatar  avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.