集合的实现2--使用数组

来源:互联网 发布:依伊芭莎淘宝 编辑:程序博客网 时间:2024/06/17 17:37

上节我们使用了对象来实现集合类,这节我们使用数组来实现同样的功能

/*使用数组来模拟集合*/function Set() {var items = [];this.add = function (value) {if(this.has(value)) {return false;}items.push(value);return true;}this.has = function (value) {if(items.indexOf(value) == -1) {return false;}return true;}this.remove = function (value) {if(this.has(value)) {var index = items.indexOf(value);items.splice(index, 1);return true;}return false;}this.clear = function () {items = [];}this.size = function () {return items.length;}this.values = function () {return items;}this.print = function () {console.log(items);}this.union = function (other_set) {var new_set = new Set();var values = this.values();for(var i=0; i<values.length; ++i) {new_set.add(values[i]);}values = other_set.values();for(var i=0; i<values.length; ++i) {if(!new_set.has(values[i])) {new_set.add(values[i]);}}return new_set;}this.intersection = function (other_set) {var new_set = new Set();var values = this.values();for(var i=0; i<values.length; ++i) {if(other_set.has(values[i])) {new_set.add(values[i]);}}return new_set;}this.difference = function (other_set) {var new_set = new Set();var values = this.values();for(var i=0; i<values.length; ++i) {if(!other_set.has(values[i])) {new_set.add(values[i]);}}return new_set;}this.isSubset = function (other_set) {var flag = true;var values = other_set.values();for(var i=0; i<values.length; ++i) {if(!this.has(values[i])) {return false;}}return true;}}function getSet(arr) {var set = new Set();for(var i=0; i<arr.length; ++i) {set.add(arr[i]);}return set;}var arr1 = [1, 1, 2, 2, 3, 2, 4]  var set1 = getSet(arr1); // set : [1, 2, 3, 4];var arr2 = [1, 4, 5, 4, 4, 6];var set2 = getSet(arr2);


阅读全文
0 0
原创粉丝点击