js Set All In One
js Set All In One
交集、并集、补集、差集
function es5Set () {
this.items = [];
this.size = this.items.length;
this.has = function (value) {
if(this.items.includes(value)) {
return true;
} else {
return false;
}
};
this.add = function (value) {
if(!this.has(value)) {
this.items.push(value);
}
return this;
};
this.delete = function (value) {
const index = this.items.indexOf(value);
// const index = this.items.findIndex(item => item === value);
this.items.splice(index, 1);
};
this.clear = function () {
this.items = [];
};
this.values = function () {
return this.items;
};
this.keys = function () {
return this.values();
};
this.entries = function () {
const matrix = [];
for (const [index, item] of this.items.entries()) {
matrix.push([
index,
item,
]);
}
return matrix;
};
this.forEach = function (callbackFn, thisArg) {
for (const item of this.items) {
const obj = {
value: item,
key: item,
set: this,
};
callbackFn(obj, this.arguments);
}
};
// TODO: 交集、并集、补集、差集 (ES6 static 方法 / ES5 prototype 方法)
this.prototype.intersection = function () {
//
};
this.union = function () {
//
};
this.complement = function () {
//
};
this.difference = function () {
//
};
}
es5Set.prototype.intersection = function () {
//
};
MDN Set
Set forEach
The forEach() method executes a provided function once for each value in the Set object, in insertion order.
Set.prototype.forEach()
const log = console.log;
const set = new Set(['foo', 'bar', undefined]);
const es6Log = (value, key, set) => {
log('\n');
log('ES6: value, key, set =', value, key, set);
log('ES6: this.arguments', this.arguments);
};
set.forEach(es6Log, this.arguments);
log('\n\n');
function es5Log(value, key, set) {
log('\n');
log('ES5: value, key, set =', value, key, set);
log('ES5: this.arguments', this.arguments);
}
set.forEach(es5Log, this.arguments);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
refs
https://githubhelp.com/loiane/javascript-datastructures-algorithms
https://github.com/loiane/javascript-datastructures-algorithms
https://github.com/loiane/javascript-datastructures-algorithms/tree/main/test/js
https://github.com/loiane/javascript-datastructures-algorithms/tree/main/test/ts
https://github.com/loiane/javascript-datastructures-algorithms/tree/main/test/ts/data-structures
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15838321.html
未经授权禁止转载,违者必究!