queues.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. QUEUES
  3. Queues are glorified Arrays and rather useful for things like our
  4. cube.twistQueue, cube.taskQueue, etc.
  5. */
  6. export function Queue( validation ){
  7. // Do we want to run a validation routine on objects being stored in
  8. // this Queue? If so you can send the function as an argument to the
  9. // constructor or create this property later on your own.
  10. if( validation !== undefined && validation instanceof Function ) this.validate = validation
  11. // The rest is vanilla.
  12. this.history = []
  13. this.future = []
  14. this.isReady = true
  15. this.isLooping = false
  16. }
  17. // The idea here with .add() is that .validate() will always return an Array.
  18. // The reason for this is that the validator may decide it needs to add more
  19. // than one element to the Queue. This allows it to do so.
  20. Queue.prototype.add = function(){
  21. var
  22. elements = Array.prototype.slice.call( arguments ),
  23. _this = this
  24. if( this.validate !== undefined && this.validate instanceof Function ) elements = this.validate( elements )
  25. if( elements instanceof Array ){
  26. elements.forEach( function( element ){
  27. _this.future.push( element )
  28. })
  29. }
  30. }
  31. Queue.prototype.empty = function(){
  32. this.future = []
  33. }
  34. Queue.prototype.do = function(){
  35. if( this.future.length ){
  36. var element = this.future.shift()
  37. this.history.push( element )
  38. return element
  39. }
  40. else if( this.isLooping ){
  41. this.future = this.history.slice()
  42. this.history = []
  43. }
  44. }
  45. Queue.prototype.undo = function(){
  46. if( this.history.length ){
  47. var element = this.history.pop()
  48. this.future.unshift( element )
  49. return element
  50. }
  51. }
  52. Queue.prototype.redo = function(){
  53. this.do()
  54. }