TreeSet.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import Collection from './Collection'
  2. import NoSuchElementException from './NoSuchElementException'
  3. import UnsupportedOperationException from '../lang/UnsupportedOperationException'
  4. import SortedSet from './SortedSet'
  5. /**
  6. * @see http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html
  7. */
  8. export default class TreeSet extends SortedSet {
  9. constructor(o) {
  10. super()
  11. this.array = []
  12. if (o instanceof Collection)
  13. this.addAll(o)
  14. }
  15. contains(o) {
  16. for (const e of this.array)
  17. if (e.compareTo(o) === 0)
  18. return true
  19. return false
  20. }
  21. add(o) {
  22. if (this.contains(o))
  23. return false
  24. for (let i = 0, len = this.array.length; i < len; i++) {
  25. const e = this.array[i]
  26. if (e.compareTo(o) === 1)
  27. return !!this.array.splice(i, 0, o)
  28. }
  29. this.array.push(o)
  30. return true
  31. }
  32. addAll(c) {
  33. for (const e of c)
  34. this.add(e)
  35. return true
  36. }
  37. remove() {
  38. throw new UnsupportedOperationException()
  39. }
  40. size() {
  41. return this.array.length
  42. }
  43. isEmpty() {
  44. return this.array.length === 0
  45. }
  46. toArray() {
  47. return this.array.slice()
  48. }
  49. iterator() {
  50. return new Iterator(this.array)
  51. }
  52. }
  53. class Iterator {
  54. constructor(array) {
  55. this.array = array
  56. this.position = 0
  57. }
  58. next() {
  59. if (this.position === this.array.length)
  60. throw new NoSuchElementException()
  61. return this.array[this.position++]
  62. }
  63. hasNext() {
  64. return this.position < this.array.length
  65. }
  66. remove() {
  67. throw new UnsupportedOperationException()
  68. }
  69. }