Guest User

Untitled

a guest
Dec 15th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. queueCreator = () => {
  2. const queue = []
  3. return {
  4. add(x) {
  5. queue.unshift(x)
  6. },
  7. remove() {
  8. if (queue.length === 0) {
  9. return undefined
  10. }
  11. return queue.pop()
  12. },
  13. next() {
  14. if (queue.length === 0) {
  15. return undefined
  16. }
  17. return queue[queue.length - 1]
  18. },
  19. get length() {
  20. return queue.length
  21. },
  22. empty() {
  23. return queue.length === 0
  24. }
  25. }
  26. }
  27.  
  28. nodeCreator = (id) => {
  29. const neighbors = []
  30. return {
  31. id,
  32. neighbors,
  33. addNeighbors(node) {
  34. neighbors.push(node)
  35. }
  36. }
  37. }
  38.  
  39. graphCreator = (uni = false) {
  40. const nodes = []
  41. const edges = []
  42. return {
  43. uni,
  44. nodes,
  45. edges,
  46. addNode(id) {
  47. nodes.push(nodeCreator(id))
  48. },
  49. searchNode(id) {
  50. return nodes.find(n => n.id === id)
  51. },
  52. addEdge(idOne, idTwo) {
  53. const a = this.searchNode(idOne)
  54. const b = this.searchNode(idTwo)
  55.  
  56. a.addNeighbors(b)
  57. if (!uni) {
  58. b.addNeighbors(a)
  59. }
  60. edges.push(`${idOne}${idTwo}`)
  61. },
  62. display() {
  63. return nodes.map(({neighbors, id}) => {
  64. let output = `${id}`
  65. if (neighbors.length) {
  66. output += ` => ${neighbors.map(node => node.id).join(' ')}`
  67. }
  68. return output
  69. }).joing('\n')
  70. },
  71. }
  72. }
Add Comment
Please, Sign In to add comment