当前位置:网站首页>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);
边栏推荐
- 高德地图测试用例
- Leetcode14 最长公共前缀
- (C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
- (C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
- Find the common ancestor of any two numbers in a binary tree
- FastDateFormat为什么线程安全
- Lekao: 22 year first-class fire engineer "technical practice" knowledge points
- 考研英语二大作文模板/图表作文,英语图表作文这一篇就够了
- 5g era, learning audio and video development, a super hot audio and video advanced development and learning classic
- String palindrome hash template question o (1) judge whether the string is palindrome
猜你喜欢
随机推荐
Simple understanding of ThreadLocal
子线程获取Request
分布式机器学习框架与高维实时推荐系统
Map and set
Take you ten days to easily finish the finale of go micro services (distributed transactions)
Multiply LCA (nearest common ancestor)
(C language) octal conversion decimal
LeetCode—<动态规划专项>剑指 Offer 19、49、60
高德地图测试用例
CONDA common command summary
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
Go learning notes - multithreading
甜心教主:王心凌
Intel internal instructions - AVX and avx2 learning notes
Less than three months after the programmer was hired, the boss wanted to launch the app within one month. If he was dissatisfied, he was dismissed immediately
Go学习笔记—多线程
Leetcode209 subarray with the smallest length
Leetcode922 sort array by parity II
Drools dynamically add, modify, and delete rules
kubenetes中port、targetPort、nodePort、containerPort的区别与联系








