Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created December 21, 2018 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndrewRayCode/6b65b844e0515c63c4b067dda4674ddf to your computer and use it in GitHub Desktop.
Save AndrewRayCode/6b65b844e0515c63c4b067dda4674ddf to your computer and use it in GitHub Desktop.
const getStackTo = (node, find, stack = []) => {
if (node === find) {
return stack;
}
if (!node.children) {
return;
}
if (node.children === find) {
return [...stack, 'children'];
}
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
const found = getStackTo(child, find, [...stack, 'children', i]);
if (found) {
return found;
}
}
};
const replaceAtStack = (node, [key, ...rest], replacement) => {
return Array.isArray(node)
? [
...node.slice(0, key),
rest.length === 0
? replacement
: replaceAtStack(node[key], rest, replacement),
...node.slice(key + 1)
]
: {
...node,
[key]:
rest.length === 0
? replacement
: replaceAtStack(node[key], rest, replacement)
};
};
const replaceNodeInAst = (ast, node, replacement) => {
const stack = getStackTo(ast, node);
if (!stack) {
throw new Error('Node not found in ast!');
}
return replaceAtStack(ast, stack, replacement);
};
const a = {
children: [
{
t: '2'
},
{
y: '3',
children: [
'hi',
{
t: 4
}
]
}
],
parent: 2
};
const q = a.children[1].children;
console.log(JSON.stringify(replaceNodeInAst(a, q, 'byeeee'), null, 2));
/**
* logs
* {
* "children": [
* {
* "t": "2"
* },
* {
* "y": "3",
* "children": "byeeee"
* }
* ],
* "parent": 2
* }
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment