当前位置:网站首页>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);
边栏推荐
- On data preprocessing in sklearn
- Addition, deletion, modification and query of MySQL table (Advanced)
- CONDA common command summary
- CDA数据分析——Excel数据处理的常见知识点归纳
- 高性能纠删码编码
- BOM DOM
- The most understandable f-string tutorial in history, collecting this one is enough
- Jenkins voucher management
- Multiply LCA (nearest common ancestor)
- arcgis js 4.x 地图中加入图片
猜你喜欢

mysql索引和事务

Go学习笔记—多线程

【C语言】十进制数转换成二进制数

刷题---二叉树--2

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

Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer

Adding database driver to sqoop of cdh6

This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry

Anxiety of a 211 programmer: working for 3 years with a monthly salary of less than 30000, worried about being replaced by fresh students

Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
随机推荐
Leetcode122 the best time to buy and sell stocks II
SSH automatically disconnects (pretends to be dead) after a period of no operation
Multiply LCA (nearest common ancestor)
上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
Jenkins user rights management
FastDateFormat为什么线程安全
[C language] Yang Hui triangle, customize the number of lines of the triangle
[C language] convert decimal numbers to binary numbers
post请求体内容无法重复获取
Why do programmers have the idea that code can run without moving? Is it poisonous? Or what?
高性能纠删码编码
When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
CDH存在隐患 : 该角色的进程使用的交换内存为xx兆字节。警告阈值:200字节
Go learning notes - go based interprocess communication
mysql数据库基础
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
LeetCode—剑指 Offer 51. 数组中的逆序对
CPU指令集介绍
[I'm a mound pytorch tutorial] learning notes
Adding database driver to sqoop of cdh6