关键概念

无序

不重复

并集、交集

定义

跟高中的集合概念一模一样

交并补集

代码实现

  1. function cusSet() {
  2. this.dataStore = []
  3. this.add = add
  4. this.contains = contains
  5. this.delete = del
  6. this.show = show
  7. this.size = size
  8. this.union = union
  9. this.intersection = intersection
  10. this.complementary = complementary
  11. this.hasSubSet = hasSubSet
  12. }
  13. function add (el) {
  14. if (!this.contains(el)) {
  15. this.dataStore.push(el)
  16. }
  17. }
  18. function contains (el) {
  19. if (this.dataStore.indexOf(el) > -1) {
  20. return true
  21. }
  22. return false
  23. }
  24. function del (el) {
  25. // if (!this.contains(el)) return false
  26. var pos = this.dataStore.indexOf(el)
  27. if (pos > -1) {
  28. this.dataStore.splice(pos, 1)
  29. return true
  30. }
  31. return false
  32. }
  33. function show () {
  34. return this.dataStore
  35. }
  36. function size () {
  37. return this.dataStore.length
  38. }
  39. // 开始实现 交并补
  40. function union (set) {
  41. // 并集
  42. var tempSet = new cusSet()
  43. for (var i = 0; i < set.size(); i++) {
  44. tempSet.add(set.dataStore[i])
  45. }
  46. for (var n = 0; n < this.size(); n++) {
  47. tempSet.add(this.dataStore[n])
  48. }
  49. return tempSet
  50. }
  51. function intersection (set) {
  52. // 交集
  53. var tempSet = new cusSet()
  54. for (i = 0; i < set.size(); i++) {
  55. if (this.contains(set.dataStore[i])) {
  56. tempSet.add(set.dataStore[i])
  57. }
  58. }
  59. return tempSet
  60. }
  61. function complementary (set) {
  62. // 补集
  63. var tempSet = new cusSet()
  64. for (i = 0; i < set.size(); i++) {
  65. if (!this.contains(set.dataStore[i])) {
  66. tempSet.add(set.dataStore[i])
  67. }
  68. }
  69. return tempSet
  70. }
  71. // 判断子集
  72. function hasSubSet(set) {
  73. if (set.size() > this.size()) return false
  74. for (i = 0; i < set.size(); i++) {
  75. if (!this.contains(set.dataStore[i])) {
  76. return false
  77. }
  78. }
  79. return true
  80. }
  81. var class1 = new cusSet()
  82. class1.add('小明')
  83. class1.add('小张')
  84. class1.add('小红')
  85. class1.add('jacky')
  86. var class2 = new cusSet()
  87. class2.add('小红')
  88. // class2.add('小绿')
  89. class2.add('jacky')
  90. class2.add('jacky2')
  91. class2.add('jacky3')
  92. class2.add('jacky4')
  93. class2.add('jacky5')
  94. class2.add('jacky6')
  95. console.log((class1.intersection(class2)).show())
  96. console.log((class1.union(class2)).show())
  97. console.log((class1.complementary(class2)).show())
  98. console.log(class1.hasSubSet(class2))