当前位置:网站首页>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);
边栏推荐
- 使用Sqoop把ADS层数据导出到MySQL
- Intel 内部指令 --- AVX和AVX2学习笔记
- drools中then部分的写法
- LeetCode—<动态规划专项>剑指 Offer 19、49、60
- CDA data analysis -- Introduction and use of aarrr growth model
- Leetcode922 sort array by parity II
- Fastdateformat why thread safe
- PyTorch nn. Full analysis of RNN parameters
- 分布式机器学习框架与高维实时推荐系统
- [FFH] little bear driver calling process (take calling LED light driver as an example)
猜你喜欢

甜心教主:王心凌

Use sqoop to export ads layer data to MySQL

Go学习笔记—多线程

Lekao: 22 year first-class fire engineer "technical practice" knowledge points

Docker-compose配置Mysql,Redis,MongoDB

kubenetes中port、targetPort、nodePort、containerPort的区别与联系

AI mid stage technology research

Go learning notes - multithreading

二分刷题记录(洛谷题单)区间的甄别

中国交通标志检测数据集
随机推荐
The differences and relationships among port, targetport, nodeport and containerport in kubenetes
【工控老马】西门子PLC Siemens PLC TCP协议详解
[C language] Yang Hui triangle, customize the number of lines of the triangle
Leetcode922 sort array by parity II
Writing method of then part in drools
考研英语二大作文模板/图表作文,英语图表作文这一篇就够了
Sort---
Sweetheart leader: Wang Xinling
Introduction to CPU instruction set
[FFH] little bear driver calling process (take calling LED light driver as an example)
高德地图测试用例
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
drools动态增加、修改、删除规则
H5 to app
AI中台技术调研
MySQL与PostgreSQL抓取慢sql的方法
5g era, learning audio and video development, a super hot audio and video advanced development and learning classic
Go learning notes - go based interprocess communication
分布式机器学习框架与高维实时推荐系统
Is the neural network (pinn) with embedded physical knowledge a pit?