JSFiddle - React, Tailwind, and code Playground

by mcsf

HTML

<pre><code id="stateContainer"></code></pre>
<div id="blocksContainer"></div>

JavaScript

let state = {
	selectedBlockNode: null,
  selectedBlockAddr: null,
  blocks: {
  	'' : '(root)',
  	'a': 'Block A',
    'b': 'Block B',
    'c': 'Block C',
  },
  order: makeNode('', [
  	makeNode('a'),
    makeNode('b'),
  ])
}

function update() {
	stateContainer.innerText = JSON.stringify(state, null, 2)
  blocksContainer.innerHTML = `<ol>${
  	JSON.stringify(treeMap(
    	Block,
      state.order
    ), null, 2)
	}</ol>`
}

function Block(blockId, blockAddr) {
	return `<li>
  	${state.blocks[blockId]}
	  <ol>${
    	children(blockAddr).map(Block).join('')
    }</ol>
	</li>`
}

function children() {
	return []
}





function makeNode(value, children = []) {
	console.assert(value !== undefined)
	return { value, children }
}

function treeFind(predicate, node) {
	if (! node) return false
	if (predicate(node)) return node
	for (let n of node.children) {
		const found = treeFind(predicate, n)
		if (found) return found
	}
}

function treeMap(mapper, node) {
	if (! node) return null
	const newNode = {
		value: mapper(node.value),
		children: [],
	}
	for (let n of node.children) {
		newNode.children.push(treeMap(mapper, n))
	}
	return newNode
}

function treeGet(path = [], node) {
	if (! path.length) return node
	const [index, ...rest] = path
	return treeGet(
		rest,
		node.children[index]
	)
}






update()