GithubHelp home page GithubHelp logo

marcelklehr / toposort Goto Github PK

View Code? Open in Web Editor NEW
299.0 6.0 39.0 173 KB

Topologically sort directed acyclic graphs (such as dependency lists) in javascript

License: Other

JavaScript 97.40% Makefile 2.60%
toposort directed-edges javascript vertices edges

toposort's Introduction

Toposort

Sort directed acyclic graphs

Build Status

Installation

npm install toposort or component install marcelklehr/toposort

then in your code:

toposort = require('toposort')

Usage

We want to sort the following graph.

graph

// First, we define our edges.
var graph = [
  ['put on your shoes', 'tie your shoes']
, ['put on your shirt', 'put on your jacket']
, ['put on your shorts', 'put on your jacket']
, ['put on your shorts', 'put on your shoes']
]


// Now, sort the vertices topologically, to reveal a legal execution order.
toposort(graph)
// [ 'put on your shirt'
// , 'put on your shorts'
// , 'put on your jacket'
// , 'put on your shoes'
// , 'tie your shoes' ]

(Note that there is no defined order for graph parts that are not connected -- you could also put on your jacket after having tied your shoes...)

Sorting dependencies

It is usually more convenient to specify dependencies instead of "sequences".

// This time, edges represent dependencies.
var graph = [
  ['tie your shoes', 'put on your shoes']
, ['put on your jacket', 'put on your shirt']
, ['put on your shoes', 'put on your shorts']
, ['put on your jacket', 'put on your shorts']
]

toposort(graph) 
// [ 'tie your shoes'
// , 'put on your shoes'
// , 'put on your jacket'
// , 'put on your shirt'
// , 'put on your shorts' ]

// Now, reversing the list will reveal a legal execution order.
toposort(graph).reverse() 
// [ 'put on your shorts'
// , 'put on your shirt'
// , 'put on your jacket'
// , 'put on your shoes'
// , 'tie your shoes' ]

API

toposort(edges)

  • edges {Array} An array of directed edges describing a graph. An edge looks like this: [node1, node2] (vertices needn't be strings but can be of any type).

Returns: {Array} a list of vertices, sorted from "start" to "end"

Throws an error if there are any cycles in the graph.

toposort.array(nodes, edges)

  • nodes {Array} An array of nodes
  • edges {Array} An array of directed edges. You don't need to mention all nodes here.

This is a convenience method that allows you to define nodes that may or may not be connected to any other nodes. The ordering of unconnected nodes is not defined.

Returns: {Array} a list of vertices, sorted from "start" to "end"

Throws an error if there are any cycles in the graph.

Tests

Run the tests with node test.js.

Legal

MIT License

toposort's People

Contributors

apaleslimghost avatar dandelany avatar jedwards1211 avatar jkroso avatar marcelklehr avatar supersam654 avatar vendethiel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

toposort's Issues

Version 1.0.0

Hello, could we bump up the version to 1.0.0 please?

Quoting from semver:

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

There are already many users (dependents) counting on this module's API and functionality, and stability of that.

Also by moving beyond 0.x version range, it's easier for us users to decide what upgrade strategy we want to use (^ to get all compatible updates, ~ to get bug fixes only).

@marcelklehr @jkroso

Cyclic dependency error

Latest release causes:

Error: Cyclic dependency: "[object Object]"
    at visit (/app/node_modules/toposort/index.js:32:13)
    at visit (/app/node_modules/toposort/index.js:48:9)
    at Function.toposort [as array] (/app/node_modules/toposort/index.js:25:22)
    at Object.module.exports.dependency (/app/node_modules/html-webpack-plugin/lib/chunksorter.js:55:19)
    at HtmlWebpackPlugin.sortChunks (/app/node_modules/html-webpack-plugin/index.js:347:33)
    at Compiler.<anonymous> (/app/node_modules/html-webpack-plugin/index.js:72:19)
    at Compiler.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:206:13)
    at Compiler.emitAssets (/app/node_modules/webpack/lib/Compiler.js:308:7)
    at onCompiled (/app/node_modules/webpack/lib/Compiler.js:247:11)
    at /app/node_modules/webpack/lib/Compiler.js:499:13
    at next (/app/node_modules/tapable/lib/Tapable.js:202:11)
    at Compiler.<anonymous> (/app/node_modules/webpack/lib/CachePlugin.js:62:5)
    at Compiler.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:206:13)
    at /app/node_modules/webpack/lib/Compiler.js:496:10
    at Compilation.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:195:46)
    at self.applyPluginsAsync.err (/app/node_modules/webpack/lib/Compilation.js:649:19)
    at Compilation.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:195:46)
    at self.applyPluginsAsync.err (/app/node_modules/webpack/lib/Compilation.js:640:11)
    at next (/app/node_modules/tapable/lib/Tapable.js:202:11)
    at Compilation.compilation.plugin (/app/node_modules/webpack/lib/optimize/UglifyJsPlugin.js:230:5)
    at next (/app/node_modules/tapable/lib/Tapable.js:204:14)
    at Compilation.compilation.plugin (/app/node_modules/webpack/lib/optimize/UglifyJsPlugin.js:230:5)
    at Compilation.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:206:13)
    at self.applyPluginsAsync.err (/app/node_modules/webpack/lib/Compilation.js:635:10)
    at next (/app/node_modules/tapable/lib/Tapable.js:202:11)
    at ExtractTextPlugin.<anonymous> (/app/node_modules/extract-text-webpack-plugin/index.js:345:4)
    at Compilation.applyPluginsAsyncSeries (/app/node_modules/tapable/lib/Tapable.js:206:13)
    at sealPart2 (/app/node_modules/webpack/lib/Compilation.js:631:9)
    at next (/app/node_modules/tapable/lib/Tapable.js:202:11)
    at ExtractTextPlugin.<anonymous> (/app/node_modules/extract-text-webpack-plugin/index.js:317:5)

Let me know if you need more information ;)

Does not work for nodes that have multiple dependencies

When a depends on b and on c I would assume the following call is correct:

toposort([['a', 'b'], ['a', 'c']]);

However it produces this output:

['a', 'a', 'c', 'b']

It this a bug? If no, how do I express the above dependency?

How do you handle a node that has no dependency on anything else?

So, imagine you have nodes A, B, C and edges C -> B. Nothing is dependent on A and A is not dependent on anything else, so it won't show up in your edges.

RIght now, it seems I have to track those separately and add them back in to the result after calling toposort.

Might be nice if we could represent it like this:

toposort([['a'],['c','b']])

Wrong sort example?

var ediges = [ [ 'a' ],
  [ 'c', 'b' ],
  [ 'c' ],
  [ 'd' ],
  [ 'c', 'd', 'g', 'a', 'e' ],
  [ 'a', 'b', 'f' ],
  [ 'd', 'g' ] ]

result is : [ 'a', 'c', 'b', 'd', undefined, 'g' ]

expect something like [ 'c', 'd', 'g', 'a', 'b', 'e', 'f' ]

Error in the "Unknown Node" test and Vows runner hangs

There's a slight syntax error here (you are missing a comma): https://github.com/marcelklehr/toposort/blob/master/test.js#L85

'unknown nodes in edges':
  { topic: function() {
      return toposort.array(['bla']  // this is the culprit
      [ ["foo", 'bar']
      , ["bar", "ron"]
      , ["john", "bar"]
      , ["tom", "john"]
      , ["ron", "tom"]
      ])
    }
  , 'should throw an exception': function(_, val) {
      console.log(val);
      assert.instanceOf(val, Error)
    }
  }

The actual error being caught is TypeError: Cannot read property 'length' of undefined when it should be something about the "Unknown Node".

When I add the comma to where it's supposed to go, I'm not receiving an error: expected [ 'bla' ] to be an instance of Error. Looking at the code, I'm not even sure an "unknown node" error is even possible since the check for the node's existence (!~nodes.indexOf(node)) is done in a loop over the node array you are making checks against (in pseudo code, it's something like for (node in nodes) if (!nodes.includes(node)) throw new Error() ).

I should also add that the Vows runner for this particular version is hanging for me:

screen shot 2018-02-23 at 7 36 30 pm

I would be happy to contribute a fix, however, I'm currently working against @supersam654's version, where (for whatever reason) the Vows runner terminates correctly:

screen shot 2018-02-23 at 7 37 50 pm

If you accept @supersam654's PR, I would like to submit a PR with custom errors. I'm building a Dependency Injection framework and I need to know which node fails the Cyclic Dependency check (and I don't want to parse the error message).

By the way, thanks for your work with toposort. I was previously working with Hapi's topo framework and I find your library to be much cleaner.

Throws "cyclic dependency" error where there is none

Again if I am not mistaken the following is a bug.

If a depdends on b & c and b also depends on c this is perfectly fine. However the following call results in an error:

toposort([['a', 'b'], ['a', 'c'], ['b', 'c']]);

On Cyclical Dependency Error: Include Id Property In Error Object?

Hey!

Great npm package for topological sort. I was wondering if perhaps the error that's thrown when getting a cyclical dependency could be made to include the node id as a property in the error object instead of having to split the error message string to get to it?

Deno support

Can you please add Deno support?
Since this project doesn't have any dependency it should be fairly easy

Exclude graph.jpg from (NPM) package

Hi,

I just noticed the file graph.jpg on my computer, since it was downloaded through NPM (although I'm not sure which of the packages on my computer depend on it).

I think it would be better to create a separate build package to distribute on NPM.

According to NPM, this package has been downloaded 1.153.649 times last month. The graph.jpg image is 10 KB. This means that only last month, 11.53649 gigabytes have been spent on downloading an image which is only using in the ReadMe :(

Other libs have a build task for building the distributed package, I think this would be a nice one for this repo as well.

Cheers!

Allow passing a sort function as a tie breaker

I'm not sure how difficult this would be. But it would be nice to be able to pass a sort function that would act as a tie breaker so that the final order would always be deterministic.

Case:
A and B both depend on C

  A
 /
C
 \
  B

if edges are passed as

[  [c, a],  [c, b] ]

vs

[  [c, b],  [c, a] ]

The result is different.

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.