当前位置:网站首页>Deep copy event bus
Deep copy event bus
2022-07-02 12:27:00 【There is no water in the sea】
One 、 Deep copy
1、JSON.stringify
2、 edition 1 : Custom deep copy - Basic implementation
// Determine whether a value is an object
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue) {
// Judge the incoming originValue Whether it is an object type
if (!isObject(originValue)) {
return originValue;
}
const newObject = {
};
for (const key in originValue) {
newObject[key] = deepClone(originValue[key]);
}
return newObject;
}
// Test code
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: " Guangzhou ",
},
},
};
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
3、 edition 2 : Custom deep copy - Array 、 function 、Symbol、Set、Map Copy
// Determine whether a value is an object
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue) {
// Judge whether it is a Set type
if (originValue instanceof Set) {
return new Set([...originValue]);
}
// Judge whether it is a Map type
if (originValue instanceof Map) {
return new Map([...originValue]);
}
// Judge if yes Symbol Of value, Then create a new one Symbol
if (typeof originValue === "symbol") {
return Symbol(originValue.description);
}
// Judgment function , Direct reuse of functions , No need to copy ,this It is also dynamically bound
if (typeof originValue === "function") {
return originValue;
}
// Judge the incoming originValue Whether it is an object type
if (!isObject(originValue)) {
return originValue;
}
// Determine whether the incoming object is an array , Or ordinary objects
const newObject = Array.isArray(originValue) ? [] : {
};
for (const key in originValue) {
newObject[key] = deepClone(originValue[key]);
}
// Symbol As key,for It can't be traversed
// Yes Symbol Of key Take special care of
const symbolKeys = Object.getOwnPropertySymbols(originValue);
for (const sKey of symbolKeys) {
newObject[sKey] = deepClone(originValue[sKey]);
}
return newObject;
}
let s1 = Symbol("aaa");
let s2 = Symbol("bbb");
// Test code
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: " Guangzhou ",
},
},
hobbies: ["a", "b", "c"],
foo: function () {
console.log("foo");
},
[s1]: "abc",
s2: s2,
set: new Set(["a", "b", "c"]),
map: new Map([
["aaa", "bbb"],
["bbb", "ccc"],
]),
};
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
3、 edition 3 : Custom deep copy - Processing of circular references
// Determine whether a value is an object
function isObject(value) {
const valueType = typeof value;
return value !== null && (valueType === "object" || valueType === "function");
}
function deepClone(originValue, map = new WeakMap()) {
// Judge whether it is a Set type
if (originValue instanceof Set) {
return new Set([...originValue]);
}
// Judge whether it is a Map type
if (originValue instanceof Map) {
return new Map([...originValue]);
}
// Judge if yes Symbol Of value, Then create a new one Symbol
if (typeof originValue === "symbol") {
return Symbol(originValue.description);
}
// Judgment function , Direct reuse of functions , No need to copy ,this It is also dynamically bound
if (typeof originValue === "function") {
return originValue;
}
// Judge the incoming originValue Whether it is an object type
if (!isObject(originValue)) {
return originValue;
}
if(map.has(originValue)) {
return map.get(originValue)
}
// Determine whether the incoming object is an array , Or ordinary objects
const newObject = Array.isArray(originValue) ? [] : {
};
map.set(originValue, newObject);
for (const key in originValue) {
newObject[key] = deepClone(originValue[key], map);
}
// Symbol As key,for It can't be traversed
// Yes Symbol Of key Take special care of
const symbolKeys = Object.getOwnPropertySymbols(originValue);
for (const sKey of symbolKeys) {
newObject[sKey] = deepClone(originValue[sKey], map);
}
return newObject;
}
let s1 = Symbol("aaa");
let s2 = Symbol("bbb");
// Test code
const obj = {
name: "chen",
age: 23,
friends: {
name: "zhangsan",
address: {
city: " Guangzhou ",
},
},
hobbies: ["a", "b", "c"],
foo: function () {
console.log("foo");
},
[s1]: "abc",
s2: s2,
set: new Set(["a", "b", "c"]),
map: new Map([
["aaa", "bbb"],
["bbb", "ccc"],
]),
};
// There's a circular reference problem
obj.info = obj;
const newObj = deepClone(obj);
console.log(newObj === obj);
obj.friends.name = "lisi";
console.log(newObj);
Two 、 Event bus
class MYEventBus {
constructor() {
this.eventBus = {
};
}
on(eventName, eventCallback, thisArg) {
let handlers = this.eventBus[eventName];
if (!handlers) {
handlers = [];
this.eventBus[eventName] = handlers;
}
handlers.push({
eventCallback, thisArg });
}
off(eventName, eventCallback) {
let handlers = this.eventBus[eventName];
if (!handlers) {
return;
}
const newHandlers = [...handlers];
for (let i = 0; i < newHandlers.length; i++) {
const handler = newHandlers[i];
if (handler.eventCallback === eventCallback) {
const index = handlers.indexOf(handler);
handlers.splice(index, 1);
}
}
}
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName];
if (!handlers) {
return;
}
handlers.forEach((handler) => {
handler.eventCallback.apply(handler.thisArg, payload);
});
}
}
const eventBus = new MYEventBus();
// main.js, monitor , Parameters : Event name , Parameters passed with payload
eventBus.on(
"abc",
function (payload) {
console.log(" monitor abc", this);
},
{
name: "zhangsan" }
);
// It can monitor multiple events
const handleCallback = function (payload) {
console.log(" monitor abc", this);
};
eventBus.on("abc", handleCallback, {
name: "zhangsan" });
// utils.js
eventBus.emit("abc", 123);
// remove
eventBus.off("abc", handleCallback);
eventBus.emit("abc", 123);
边栏推荐
- Simple understanding of ThreadLocal
- Initial JDBC programming
- (C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
- Map and set
- Error in kubeadm join: [error port-10250]: port 10250 is in use [error fileavailable--etc kubernetes PKI
- Leetcode - Sword finger offer 37, 38
- LeetCode—<动态规划专项>剑指 Offer 19、49、60
- 字符串回文hash 模板题 O(1)判字符串是否回文
- Distributed machine learning framework and high-dimensional real-time recommendation system
- Map和Set
猜你喜欢
随机推荐
Leetcode14 最长公共前缀
Leetcode topic [array] -540- single element in an ordered array
输入一个三位的数字,输出它的个位数,十位数、百位数。
Sweetheart leader: Wang Xinling
LeetCode—剑指 Offer 37、38
记录一下MySql update会锁定哪些范围的数据
Codeforces 771 div2 B (no one FST, refers to himself)
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
【C语言】杨辉三角,自定义三角的行数
drools动态增加、修改、删除规则
drools执行String规则或执行某个规则文件
MySQL与PostgreSQL抓取慢sql的方法
Drools dynamically add, modify, and delete rules
Intel internal instructions - AVX and avx2 learning notes
The most understandable f-string tutorial in history, collecting this one is enough
There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes
Leetcode922 按奇偶排序数组 II
This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry
求16以内正整数的阶乘,也就是n的阶层(0=<n<=16)。输入1111退出。
H5 to app