Skip to content

Commit

Permalink
changes
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] committed Oct 17, 2023
1 parent 2609b51 commit fa6ce8a
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/frontend-basic/js/平铺的节点转树.md
Original file line number Diff line number Diff line change
@@ -1 +1,42 @@
# 平铺的节点转树
# 平铺的节点转树

```js
function listToTree(nodes) {
const rootNodes = [];
const nodeMap = {};

// 将节点存储在哈希表中
for (let node of nodes) {
nodeMap[node.id] = { ...node, children: [] };
}

// 构建树结构
for (let node of nodes) {
// 判断当前节点是否有父节点
const parentNode = nodeMap[node.parentId];
// 如果有父节点,直接为该父节点children添加当前节点
if (parentNode) {
parentNode.children.push(nodeMap[node.id]);
} else {
// 没有父节点,直接push
rootNodes.push(nodeMap[node.id]);
}
}

return rootNodes;
}

// 平铺的节点数组示例
const nodes = [
{ id: 1, name: 'Node 1', parentId: null },
{ id: 2, name: 'Node 1.1', parentId: 1 },
{ id: 3, name: 'Node 1.1.1', parentId: 2 },
{ id: 4, name: 'Node 1.2', parentId: 1 },
{ id: 5, name: 'Node 2', parentId: null },
{ id: 6, name: 'Node 2.1', parentId: 5 }
];

// 转换为树状结构
const tree = listToTree(nodes);
console.log(tree);
```
50 changes: 50 additions & 0 deletions src/informal/每日学习.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,56 @@ asyncFunction()
```


### 实现深拷贝
```js
function getType(source) {
return Object.prototype.toString.call(source);
}

function deepCopy(source, memory) {
const isPrimitive = (value) => {
return /Number|Boolean|String|Null|Undefined|Symbol|Function/.test(
Object.prototype.toString.call(value)
);
};
let result;

memory || (memory = new WeakMap());

if (isPrimitive(source)) {
result = source;
} else if (Array.isArray(source)) {
result = source.map((value) => deepCopy(value, memory));
} else if (getType(source) === "[object Date]") {
result = new Date(source);
} else if (getType(source) === "[object Regex]") {
result = new Regex(source);
} else if (getType(source) === "[object Set]") {
result = new Set();
for (const value of source) {
result.add(deepClone(value, memory));
}
} else if (getType(source) === "[object Map]") {
result = new Map();
for (const [key, val] of source) {
result.set(key, deepCopy(val, memory));
}
} else {
if (memory.has(source)) {
result = memory.get(source);
} else {
result = Object.create(null);
memory.set(source, result);
Object.keys(source).forEach((key) => {
const value = source[key];
result[key] = deepClone(value, memory);
});
}
}
}
```



### 0.1+0.2为什么不等于0.3
在javascript中,Number类型使用的是IEEE754标准来表示浮点数,它会使用64位来存储一个浮点数。
Expand Down

0 comments on commit fa6ce8a

Please sign in to comment.