fast-list.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. ;(function() { // closure for web browsers
  2. function Item (data, prev, next) {
  3. this.next = next
  4. if (next) next.prev = this
  5. this.prev = prev
  6. if (prev) prev.next = this
  7. this.data = data
  8. }
  9. function FastList () {
  10. if (!(this instanceof FastList)) return new FastList
  11. this._head = null
  12. this._tail = null
  13. this.length = 0
  14. }
  15. FastList.prototype =
  16. { push: function (data) {
  17. this._tail = new Item(data, this._tail, null)
  18. if (!this._head) this._head = this._tail
  19. this.length ++
  20. }
  21. , pop: function () {
  22. if (this.length === 0) return undefined
  23. var t = this._tail
  24. this._tail = t.prev
  25. if (t.prev) {
  26. t.prev = this._tail.next = null
  27. }
  28. this.length --
  29. if (this.length === 1) this._head = this._tail
  30. else if (this.length === 0) this._head = this._tail = null
  31. return t.data
  32. }
  33. , unshift: function (data) {
  34. this._head = new Item(data, null, this._head)
  35. if (!this._tail) this._tail = this._head
  36. this.length ++
  37. }
  38. , shift: function () {
  39. if (this.length === 0) return undefined
  40. var h = this._head
  41. this._head = h.next
  42. if (h.next) {
  43. h.next = this._head.prev = null
  44. }
  45. this.length --
  46. if (this.length === 1) this._tail = this._head
  47. else if (this.length === 0) this._head = this._tail = null
  48. return h.data
  49. }
  50. , item: function (n) {
  51. if (n < 0) n = this.length + n
  52. var h = this._head
  53. while (n-- > 0 && h) h = h.next
  54. return h ? h.data : undefined
  55. }
  56. , slice: function (n, m) {
  57. if (!n) n = 0
  58. if (!m) m = this.length
  59. if (m < 0) m = this.length + m
  60. if (n < 0) n = this.length + n
  61. if (m <= n) {
  62. throw new Error("invalid offset: "+n+","+m)
  63. }
  64. var len = m - n
  65. , ret = new Array(len)
  66. , i = 0
  67. , h = this._head
  68. while (n-- > 0 && h) h = h.next
  69. while (i < len && h) {
  70. ret[i++] = h.data
  71. h = h.next
  72. }
  73. return ret
  74. }
  75. , drop: function () {
  76. FastList.call(this)
  77. }
  78. }
  79. if ("undefined" !== typeof(exports)) module.exports = FastList
  80. else if ("function" === typeof(define) && define.amd) {
  81. define("FastList", function() { return FastList })
  82. } else (function () { return this })().FastList = FastList
  83. })()