当前位置:网站首页>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);
边栏推荐
- Differences between nodes and sharding in ES cluster
- post请求体内容无法重复获取
- Leetcode14 longest public prefix
- Deep understanding of P-R curve, ROC and AUC
- Sort---
- String palindrome hash template question o (1) judge whether the string is palindrome
- Test shift left and right
- Performance tuning project case
- kubenetes中port、targetPort、nodePort、containerPort的区别与联系
- The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
猜你喜欢

ThreadLocal的简单理解

Distributed machine learning framework and high-dimensional real-time recommendation system

From scratch, develop a web office suite (3): mouse events

Use sqoop to export ads layer data to MySQL
![[old horse of industrial control] detailed explanation of Siemens PLC TCP protocol](/img/13/9002244555ebe8a61660c2506993fa.png)
[old horse of industrial control] detailed explanation of Siemens PLC TCP protocol

测试左移和右移

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

Map和Set

CDA数据分析——AARRR增长模型的介绍、使用

MySQL indexes and transactions
随机推荐
Leetcode - Sword finger offer 59 - I, 59 - II
lombok常用注解
Initial JDBC programming
Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
刷题---二叉树--2
高德地图测试用例
Go学习笔记—基于Go的进程间通信
kubenetes中port、targetPort、nodePort、containerPort的区别与联系
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
LeetCode—剑指 Offer 37、38
寻找二叉树中任意两个数的公共祖先
Performance tuning project case
AI mid stage technology research
排序---
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
CDA data analysis -- common knowledge points induction of Excel data processing
Leetcode topic [array] -540- single element in an ordered array
Embedded Software Engineer career planning
Maximum profit of jz63 shares