Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
OronNadiv committed Jul 7, 2016
0 parents commit 314b349
Show file tree
Hide file tree
Showing 12 changed files with 467 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
11 changes: 11 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "standard",
"globals": {
"describe": false,
"it": false,
"before": false,
"beforeEach": false,
"after": false,
"afterEach": false
}
}
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.idea
coverage
lib
node_modules
*.log
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v6
4 changes: 4 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
language: node_js
node_js:
- "6"
script: npm run test-coveralls
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 James Cready

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# BFS as Promised — Promisified Breadth-First Search.

[![NPM Version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![Code Climate][codeclimate-image]][codeclimate-url]
[![Dependencies][dependencies-image]][dependencies-url]

Asynchronous implementation of [BFS][bfs] to find the shortest path. The implementation uses [Bluebird][bluebird]'s promise.

##Example:
```javascript
const BFS = require('bfs-as-promised');
const graph = new Map([
[1, [2, 3]],
[2, [3, 4]],
[3, []],
[4, [5]]
])
const getMoves = (fromNodes) => {
const res = new Map()
return Promise
.each(fromNodes, (fromNode) => {
res.set(fromNode, graph.get(fromNode) || [])
})
.return(res)
}

const isGoal = (item) => item === 5
const bfs = new BFS(1, getMoves, isGoal)
bfs.find().then((path) => console.log(path)) // [1, 2, 4, 5]
```

##Usage:
```javascript
const bfs = new BFS(<START>, <GET_MOVES>, <IS_GOAL>)
bfs.find().then((<PATH>) => console.log(path))
```
###Parameters:
####__START__
Assuming we are trying to find the shortest path from node __A__ to node __B__. Start parameter will be node __A__.

#### getMoves(fromNodes, depth)
The function should returns a [map][map] where the key is a value from the array __fromNodes__ and the value is an array of nodes that can be reached from the given key.
<br/>The function may also return a [promise][promise] that once resolved, will return the above [map][map]

E.g. For the following graph:
```
1 -> 2
1 -> 3
2 -> 3
```
`getMoves([1, 2, 3])` should return a [map][map] with the following values:
```javascript
new Map([
[1, [2,3]],
[2, [3]],
[3, []]
])
```

#### isGoal(node)
The function should return a boolean value (true/false) where `true` means the given `node` is the "finish" node otherwise, `false`
<br/>The function may also return a [promise][promise] that once resolved, will return `true/false`.

#### find()
This function returns a promise. The promise, once resolved, will return the shorted BFS path (if exists) or null if such path does not exist.

E.g. for the following graph:
```
1 -> 2
1 -> 3
2 -> 3
2 -> 4
4 -> 5
```
calling `find()` where start is `1` and goal is `5`, will a promise that once resolved, it returns `[1, 2, 4, 5]`.
<br/>calling `find()` where start is `1` and goal is `-1`, will a promise that once resolved, it returns `null`.

[npm-image]: https://img.shields.io/npm/v/bfs-as-promised.svg?style=flat-square
[npm-url]: https://npmjs.org/package/bfs-as-promised
[travis-image]: http://img.shields.io/travis/OronNadiv/bfs-as-promised.svg?style=flat-square
[travis-url]: https://travis-ci.org/OronNadiv/bfs-as-promised
[coveralls-image]: http://img.shields.io/coveralls/OronNadiv/bfs-as-promised.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/OronNadiv/bfs-as-promised?branch=master
[dependencies-image]: https://img.shields.io/david/OronNadiv/bfs-as-promised.svg?style=flat-square
[dependencies-url]: https://david-dm.org/OronNadiv/bfs-as-promised
[codeclimate-image]: https://img.shields.io/codeclimate/github/OronNadiv/bfs-as-promised.svg?style=flat-square
[codeclimate-url]: https://codeclimate.com/github/OronNadiv/bfs-as-promised

[bluebird]: https://www.npmjs.org/package/bluebird
[bfs]: https://en.wikipedia.org/wiki/Breadth-first_search
[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
2 changes: 2 additions & 0 deletions lib/bfs.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/bfs.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 47 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "bfs-as-promised",
"version": "1.0.0",
"description": "Breadth-first search (BFS) using promise (Bluebird)",
"main": "lib/bfs.js",
"keywords": [
"bfs",
"breadth first search ",
"bluebird",
"promise"
],
"repository": {
"type": "git",
"url": "https://github.com/OronNadiv/bfs-as-promised.git"
},
"homepage": "https://github.com/OronNadiv/bfs-as-promised",
"bugs": {
"url": "https://github.com/OronNadiv/bfs-as-promised/issues"
},
"author": {
"name": "Oron Nadiv",
"email": "oron@nadiv.us"
},
"license": "MIT",
"scripts": {
"compile": "babel src --out-dir lib --source-maps --minified",
"test-coveralls": "babel-node ./node_modules/.bin/istanbul cover _mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",
"cover": "istanbul cover _mocha --include-all-sources -x **/lib/**",
"lint": "eslint . --ignore-path .gitignore",
"test": "babel-node ./node_modules/.bin/mocha"
},
"devDependencies": {
"babel-cli": "^6",
"babel-preset-es2015": "^6",
"coveralls": "^2",
"eslint": "^3",
"eslint-config-standard": "^5",
"eslint-plugin-promise": "^1",
"eslint-plugin-standard": "^1",
"istanbul": "^0.4",
"mocha": "^2",
"should": "^9"
},
"dependencies": {
"bluebird": "^3"
}
}
94 changes: 94 additions & 0 deletions src/bfs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
const Promise = require('bluebird')

class BFS {
constructor (start, getMoves, isGoal) {
this.start = start
this.getMoves = getMoves
this.isGoal = isGoal
this.visited = new Map()
this.visited.set(start, null)
this.queue = new Set()
this.queue.add(start)
}

_returnPath () {
const self = this
if (self.final === undefined) {
return null
}
let currentItem = self.final
const path = []
do {
path.splice(0, 0, currentItem)
currentItem = self.visited.get(currentItem)
} while (currentItem !== self.start)
path.splice(0, 0, currentItem)
return path
}

_fetchAdjutant (fromNodes, depth) {
return Promise
.resolve(this.getMoves(fromNodes, depth))
.tap((map) => {
if (typeof map !== 'object') {
throw new Error(`Unexpected result from getMoves.
Expected type: Object.
Actual type: ${typeof map}, value: ${map}`)
}
if (map.size !== fromNodes.length) {
throw new Error(`Unexpected result from getMoves.
Expected count: ${fromNodes.length}.
Actual count: ${map.size}`)
}
})
}

_checkIsGoal (fromNode, toNodes) {
const self = this
return Promise
.map(toNodes, (toNode) => {
if (toNode === null || toNode === undefined || self.visited.has(toNode)) {
return
}
self.visited.set(toNode, fromNode)
return Promise
.resolve(self.isGoal(toNode))
.then((isGoal) => {
if (isGoal) {
self.final = toNode
self.isDone = true
return
}
self.queue.add(toNode)
})
})
}

_processQueue (depth) {
const self = this
if (self.isDone || self.queue.size === 0) {
return Promise.resolve()
}

return Promise
.resolve(self._fetchAdjutant(Array.from(self.queue), depth))
.then((map) => {
self.queue.clear()
const promises = []
map.forEach((toNodes, fromNode) => {
promises.push(self._checkIsGoal(fromNode, toNodes, depth))
})
return Promise.all(promises)
})
.then(() => self._processQueue(depth + 1))
}

find () {
const self = this
return Promise
.resolve(self._processQueue(0))
.then(() => self._returnPath())
}
}

module.exports = BFS
Loading

0 comments on commit 314b349

Please sign in to comment.