Advertisement
Guest User

Untitled

a guest
Feb 28th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. iter_helper = (t, index) ->
  2. index += 1
  3. if index == t.n
  4. return
  5. return index, t[index]
  6.  
  7.  
  8. class Array
  9. new: =>
  10. @n = 0
  11.  
  12. @from_pack = (...) ->
  13. arr = @!
  14. arr.n = select('#', ...)
  15. for i=1,arr.n
  16. arr[i-1] = select(i, ...)
  17. arr
  18.  
  19. @from_table = (t) ->
  20. arr = @!
  21. arr.n = table.maxn(t)
  22. for i=1,arr.n
  23. arr[i-1] = t[i]
  24. arr
  25.  
  26. @from_range = (head,tail) ->
  27. arr = @!
  28. for i=head,tail
  29. arr\push i
  30. arr
  31.  
  32. @from_default = (size, default_value) ->
  33. arr = @!
  34. if default_value ~= nil
  35. for i=0,size-1
  36. arr[i] = default_value
  37. arr.n = size
  38. arr
  39.  
  40. insert: (pos, value) =>
  41. for i=@n-1,pos,-1
  42. @[i+1] = @[i]
  43. @[pos] = value
  44. @n += 1
  45. return
  46.  
  47. remove: (pos) =>
  48. assert pos >= 0 and pos < @n,
  49. "Index out of bounds. #{pos}"
  50. @n -= 1
  51. value = @[pos]
  52. for i=pos,@n
  53. @[i] = @[i+1]
  54. value
  55.  
  56. push: (value) =>
  57. @n += 1
  58. @[@n-1] = value
  59. return
  60.  
  61. pop: =>
  62. value = @[@n]
  63. @[@n] = nil
  64. @n -= 1
  65. value
  66.  
  67. iter: =>
  68. iter_helper, @, -1
  69.  
  70. maxn: =>
  71. @n
  72.  
  73. concat: =>
  74. -- TODO
  75.  
  76. sort: =>
  77. -- TODO
  78.  
  79. -- __index: (index) =>
  80. -- assert(0 <= index and index < @n,
  81. -- "Index out of bounds. #{index}")
  82. -- rawget @, index
  83.  
  84. -- __newindex: (index, v) =>
  85. -- if index == @n
  86. -- @n += 1
  87. -- rawset @, index, v
  88. -- else
  89. -- assert(0 <= index and index < @n,
  90. -- "Index out of bounds. #{index}")
  91. -- nil
  92.  
  93. __tostring: =>
  94. if @n == 0
  95. "{}"
  96. else
  97. values = tostring(@[0])
  98. for i=1,@n-1
  99. values ..= "," .. tostring(@[i])
  100. "{#{values}} #{@n}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement