Created
December 21, 2018 22:35
-
-
Save AndrewRayCode/6b65b844e0515c63c4b067dda4674ddf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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