@cmtlyt/cl-utils
Version:
105 lines (104 loc) • 3.92 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.upgradeObj = void 0;
/**
* 升级对象
* @param {object} obj
*/
function upgradeObj(obj) {
const funcMap = {
forEach(callback, thisArgs) {
const keys = Object.keys(this);
keys.forEach(key => {
callback.apply(thisArgs || this, [this[key], key, this]);
});
},
map(callback, thisArgs) {
const keys = Object.keys(this);
const list = [];
for (let i = 0; i < keys.length; i++) {
list.push(callback.apply(thisArgs || this, [this[keys[i]], keys[i], this]));
}
return list;
},
some(callback, thisArgs) {
const keys = Object.keys(this);
for (let i = 0; i < keys.length; i++) {
if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this]))
return true;
}
return false;
},
every(callback, thisArgs) {
const keys = Object.keys(this);
for (let i = 0; i < keys.length; i++) {
if (!callback.apply(thisArgs || this, [this[keys[i]], keys[i], this]))
return false;
}
return true;
},
find(callback, thisArgs) {
const keys = Object.keys(this);
for (let i = 0; i < keys.length; i++) {
if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this]))
return this[keys[i]];
}
return null;
},
filter(callback, thisArgs) {
const keys = Object.keys(this);
const newObj = {};
for (let i = 0; i < keys.length; i++) {
if (callback.apply(thisArgs || this, [this[keys[i]], keys[i], this]))
newObj[keys[i]] = this[keys[i]];
}
return newObj;
},
flat(depth, sep = '.') {
const newObj = {};
const flatFunc = (obj, depth, prefix = '') => {
for (let key in obj) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && depth > 0) {
flatFunc(obj[key], depth - 1, prefix + key + sep);
}
else {
newObj[prefix + key] = obj[key];
}
}
};
const obj = this;
flatFunc(obj, depth);
return newObj;
},
remove(keys) {
if (typeof keys === 'string') {
keys = [keys];
}
if (!Array.isArray(keys)) {
console.error('key必须是字符串数组或字符串');
}
return this.filter((_, key) => {
return !keys.includes(key);
});
},
};
for (let key in funcMap) {
Object.defineProperty(obj, key, {
value: funcMap[key],
writable: false,
enumerable: false,
configurable: false,
});
}
}
exports.upgradeObj = upgradeObj;
});