UNPKG

execution-engine

Version:

A TypeScript library for tracing and visualizing code execution workflows.

66 lines (65 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isXPath = isXPath; exports.queryByXPath = queryByXPath; exports.extract = extract; const matchingXPath = new RegExp('(\\[|\\.|\\]){1,}', 'g'); /** * tests if a given string could be an xpath (with accessors) * @param key */ function isXPath(key) { return matchingXPath.test(key); } /** * @param object object or array of objects to search in by xPath * @param xPath example: "[key=businessUnitCode].value" * @param options */ function queryByXPath(object, xPath, options) { if (Array.isArray(object) && options?.searchInArrayElements) { return options?.searchInArrayElements === 'ALL' ? object?.map((o) => queryByXPath(o, xPath))?.filter((x) => !!x) : queryByXPath(object?.find((o) => queryByXPath(o, xPath)), xPath); } return xPath .replace('[', '.[') .split('.') ?.reduce((input, acc) => { const accessor = acc.trim(); if (/^\[.*=.*\]$/.test(accessor)) { const [k, v] = accessor .replace(/(\[|\])/gi, '') .split('=') .map((i) => i.trim()); if (Array.isArray(input)) { return options?.searchInArrayElements === 'ALL' ? input?.filter((i) => i?.[k] === v) : input?.find((i) => i?.[k] === v); } if (input?.[k] === v) { return input; } } else { if (Array.isArray(input)) { if (Number.isFinite(parseInt(accessor, 10))) { return input?.[accessor]; } return options?.searchInArrayElements === 'ALL' ? input?.map((i) => i?.[accessor]) : input?.filter((i) => i?.[accessor])?.[0]?.[accessor]; } return input?.[accessor]; } }, object); } /** * * @param object object or array of objects to extract from * @param xPaths array of xPaths to queryBy * @example extract(object, ['inputs.number', 'parent', 'outputs.others.2.key', 'outputs.others[key=Y].value']) */ function extract(object, xPaths) { return xPaths.map((xp, index) => { return { [xPaths[index]]: queryByXPath(object, xPaths[index]) }; }); }