HashSet.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import Collection from './Collection'
  2. import NoSuchElementException from './NoSuchElementException'
  3. import UnsupportedOperationException from '../lang/UnsupportedOperationException'
  4. import Set from './Set'
  5. /**
  6. * @see http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html
  7. */
  8. export default class HashSet extends Set {
  9. constructor(o) {
  10. super()
  11. this.map = new Map()
  12. if (o instanceof Collection)
  13. this.addAll(o)
  14. }
  15. contains(o) {
  16. const hashCode = o.hashCode ? o.hashCode() : o
  17. if (this.map.has(hashCode))
  18. return true
  19. return false
  20. }
  21. add(o) {
  22. const hashCode = o.hashCode ? o.hashCode() : o
  23. if (this.map.has(hashCode))
  24. return false
  25. return !!this.map.set(hashCode, o)
  26. }
  27. addAll(c) {
  28. for (const e of c)
  29. this.add(e)
  30. return true
  31. }
  32. remove() {
  33. throw new UnsupportedOperationException()
  34. }
  35. size() {
  36. return this.map.size
  37. }
  38. isEmpty() {
  39. return this.map.size === 0
  40. }
  41. toArray() {
  42. return Array.from(this.map.values())
  43. }
  44. iterator() {
  45. return new Iterator(this.map)
  46. }
  47. [Symbol.iterator]() {
  48. return this.map
  49. }
  50. }
  51. class Iterator {
  52. constructor(map) {
  53. this.iterator = map.values()
  54. const { done, value } = this.iterator.next()
  55. this.done = done
  56. this.value = value
  57. }
  58. next() {
  59. if (this.done)
  60. throw new NoSuchElementException()
  61. const current = this.value
  62. const { done, value } = this.iterator.next()
  63. this.done = done
  64. this.value = value
  65. return current
  66. }
  67. hasNext() {
  68. return !this.done
  69. }
  70. remove() {
  71. throw new UnsupportedOperationException()
  72. }
  73. }