Skip to content

Commit

Permalink
MWPW-145148 Inline tree.js into fragment.js (#2052)
Browse files Browse the repository at this point in the history
* MWPW-145148 Inline tree.js into fragment.js

No code change, just a move of code in tree.js into fragment.js

* Move tree test
  • Loading branch information
chrischrischris authored Apr 8, 2024
1 parent 2680c10 commit bc5f882
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 58 deletions.
59 changes: 58 additions & 1 deletion libs/blocks/fragment/fragment.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable max-classes-per-file */
import { createTag, getConfig, loadArea, localizeLink } from '../../utils/utils.js';
import Tree from '../../utils/tree.js';

const fragMap = {};

Expand All @@ -20,6 +20,7 @@ const updateFragMap = (fragment, a, href) => {
if (!fragLinks.length) return;

if (document.body.contains(a)) { // is fragment on page (not nested)
// eslint-disable-next-line no-use-before-define
fragMap[href] = new Tree(href);
fragLinks.forEach((link) => fragMap[href].insert(href, localizeLink(removeHash(link.href))));
} else {
Expand Down Expand Up @@ -132,3 +133,59 @@ export default async function init(a) {
await loadArea(fragment);
}
}

class Node {
constructor(key, value = key, parent = null) {
this.key = key;
this.value = value;
this.parent = parent;
this.children = [];
}

get isLeaf() {
return this.children.length === 0;
}
}

export class Tree {
constructor(key, value = key) {
this.root = new Node(key, value);
}

* traverse(node = this.root) {
yield node;
if (node.children.length) {
for (const child of node.children) {
yield* this.traverse(child);
}
}
}

insert(parentNodeKey, key, value = key) {
for (const node of this.traverse()) {
if (node.key === parentNodeKey) {
node.children.push(new Node(key, value, node));
return true;
}
}
return false;
}

remove(key) {
for (const node of this.traverse()) {
const filtered = node.children.filter((c) => c.key !== key);
if (filtered.length !== node.children.length) {
node.children = filtered;
return true;
}
}
return false;
}

find(key) {
for (const node of this.traverse()) {
if (node.key === key) return node;
}
return undefined;
}
}
56 changes: 0 additions & 56 deletions libs/utils/tree.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from '@esm-bundle/chai';
import Tree from '../../libs/utils/tree.js';
import { Tree } from '../../../libs/blocks/fragment/fragment.js';

describe('Tree Data Struct', () => {
it('should create a tree with root node', () => {
Expand Down

0 comments on commit bc5f882

Please sign in to comment.