Typescript all the parser things

This commit is contained in:
Thaum Rystra
2024-02-20 23:21:12 +02:00
parent 3ea492ee78
commit ac15512bc5
86 changed files with 926 additions and 718 deletions

View File

@@ -1,16 +1,29 @@
import { get } from 'lodash';
export default function applyFnToKey(doc, key, fn){
if (key.includes('.$')){
export default function applyFnToKey(doc, key, fn) {
if (key.includes('.$')) {
applyToArrayKey(doc, key, fn);
} else {
applyToSingleKey(doc, key, fn);
}
}
function applyToSingleKey(doc, key, fn){
export async function applyFnToKeyAsync(doc, key, fn) {
if (key.includes('.$')) {
await applyToArrayKeyAsync(doc, key, fn);
} else {
await applyToSingleKeyAsync(doc, key, fn);
}
}
function applyToSingleKey(doc, key, fn) {
// call the function with the current value and document for context
fn(doc, key);
return fn(doc, key);
}
async function applyToSingleKeyAsync(doc, key, fn) {
// call the function with the current value and document for context
return await fn(doc, key);
}
/**
@@ -19,7 +32,7 @@ function applyToSingleKey(doc, key, fn){
* Warning: Order might be confusing, it will traverse the deepest array in order
* but the shallower arrays in reverse order
*/
function applyToArrayKey(doc, key, fn){
function applyToArrayKey(doc, key, fn) {
const keySplit = key.split('.$');
// Stack based depth first traversal of arrays
const array = get(doc, keySplit[0]);
@@ -30,11 +43,12 @@ function applyToArrayKey(doc, key, fn){
currentPath: keySplit[0],
indices: [],
}];
while(stack.length){
while (stack.length) {
const state = stack.pop();
for (let index in state.array){
if (!state) break;
for (let index in state.array) {
const currentPath = `${state.currentPath}[${index}]${state.paths[0]}`
if (state.paths.length == 1){
if (state.paths.length == 1) {
applyToSingleKey(doc, currentPath, fn);
} else {
const array = get(doc, currentPath);
@@ -49,3 +63,35 @@ function applyToArrayKey(doc, key, fn){
}
}
}
async function applyToArrayKeyAsync(doc, key, fn) {
const keySplit = key.split('.$');
// Stack based depth first traversal of arrays
const array = get(doc, keySplit[0]);
if (!array) return;
const stack = [{
array,
paths: keySplit.slice(1),
currentPath: keySplit[0],
indices: [],
}];
while (stack.length) {
const state = stack.pop();
if (!state) break;
for (let index in state.array) {
const currentPath = `${state.currentPath}[${index}]${state.paths[0]}`
if (state.paths.length == 1) {
await applyToSingleKey(doc, currentPath, fn);
} else {
const array = get(doc, currentPath);
if (!array) return;
stack.push({
array,
paths: state.paths.slice(1),
currentPath,
indices: [...state.indices, index],
});
}
}
}
}