分享一些自己常用的数组拓展
interface Array<T> {
// 数组相减
mul: (arr: Array<T>) => Array<T>;
// 数组相减
mulSelf: (arr: Array<T>) => Array<T>;
// 数组求和
sum: (fn?: (s: T, index: number) => number) => number;
// 判断数组相等
equal: (arr: Array<T>) => boolean;
// 数组包函
contain: (arr: Array<T>) => boolean;
// 数组初始化
memset: (len: number, map: number | string | boolean | ((idx: number) => any)) => this;
}
Object.defineProperty(Array.prototype, 'mul', {
value: function (arr: Array<any>) {
let newArr = [...this];
for (let it of arr) {
let idx = newArr.indexOf(it);
if (idx != -1) newArr.splice(idx, 1);
}
return newArr;
},
});
Object.defineProperty(Array.prototype, 'mulSelf', {
value: function (arr: Array<any>) {
for (let it of arr) {
let idx = this.indexOf(it);
if (idx != -1) this.splice(idx, 1);
else return false;
}
return true;
},
});
Object.defineProperty(Array.prototype, 'sum', {
value: function <T>(fn?: (s: T, index: number) => number) {
let num = 0;
for (let i = 0; i < this.length; i++) {
if (this[i] == null) continue;
if (!fn && typeof this[i] == 'number') num += this[i];
else if (fn) num += fn(this[i], i);
}
return num;
},
});
Object.defineProperty(Array.prototype, 'equal', {
value: function (arr: Array<any>) {
if (this.length != arr.length) return false;
return this.slice().sort().toString() == arr.slice().sort().toString();
},
});
Object.defineProperty(Array.prototype, 'contain', {
value: function (arr: Array<any>) {
let newArr = [...this];
for (let it of arr) {
let idx = newArr.indexOf(it);
if (idx == -1) return false;
newArr.splice(idx, 1);
}
return true;
},
});
Object.defineProperty(Array.prototype, 'memset', {
value: function (len: number, map: number | string | boolean | ((idx: number) => any)) {
for (let i = 0; i < len; i++) {
this[i] = typeof map === 'function' ? map(i) : map;
}
return this;
},
});
let array = [].meset(4, () => []); // [[], [], [], []];
array = [].memset(4, 1); // [1, 1, 1, 1];
let sum = array.sum(); // 4;
let array2 = [].memset(3, 1); [1, 1, 1];
let left = array.mul(array2); // [1];
let res = array.contain(array2); // true;
res = array.equal(array2); // false;