UNPKG

workspace-integrations

Version:
118 lines (117 loc) 3.45 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.emptyObj = exports.toUrlParams = exports.isFun = exports.isObj = exports.isStr = exports.pathMatch = exports.shortName = exports.sleep = exports.removePath = exports.toTree = void 0; function pathMatch(_actual, _pattern) { const actual = _actual.replace(/ /g, '.').toLowerCase(); const pattern = _pattern.replace(/ /g, '.').toLowerCase(); return actual.includes(pattern); } exports.pathMatch = pathMatch; function isStr(a) { return typeof a === 'string'; } exports.isStr = isStr; function isFun(a) { return typeof a === 'function'; } exports.isFun = isFun; function isObj(a) { return typeof a === 'object'; } exports.isObj = isObj; function shortName(deviceId) { return deviceId.slice(0, 8) + '...' + deviceId.slice(-8); } exports.shortName = shortName; function sleep(ms) { return new Promise((res) => setTimeout(res, ms)); } exports.sleep = sleep; function removePath(path, object) { // always return array if wildcard search used const retArray = path.includes('[*]'); const paths = path.replace(/ /g, '.').split('.'); let res = object; paths.forEach((key) => { // remove index for path match if (key.match(/\[.\]$/)) { key = key.slice(0, -3); } ; if (key !== '*') { if (Array.isArray(res)) { const output = []; res.forEach((i) => { output.push(i[key]); }); res = output; } else { res = res[key]; } } }); // remove array for single result if not a wildcard search if (Array.isArray(res) && res.length === 1 && !retArray) return res[0]; return res; } exports.removePath = removePath; function makeBranch(tree, key, value) { const paths = key.split('.'); let parent = tree; paths.forEach((path, i) => { const isLeaf = i === paths.length - 1; const isList = path.includes('['); if (isLeaf && !isList) { parent[path] = value; } else if (isList) { // @ts-ignore const [_full, name, index] = path.match(/(.*)\[(\d+)\]/); if (!parent[name]) { parent[name] = []; } const existingObj = parent[name].find((n) => n.id === index); if (!existingObj) { const obj = { id: index }; parent[name].push(obj); parent = obj; } else { parent = existingObj; } } else if (!parent[path]) { parent[path] = {}; parent = parent[path]; } else { parent = parent[path]; } }); } function toTree(config) { const tree = {}; const keys = Object.keys(config); keys.sort((k1, k2) => (k1 < k2 ? -1 : 1)); keys.forEach((key) => { makeBranch(tree, key, config[key].value); }); return tree; } exports.toTree = toTree; function emptyObj(obj) { return !Object.keys(obj).length; } exports.emptyObj = emptyObj; function toUrlParams(object) { if (!object) return ''; const list = []; Object.keys(object).forEach((key) => { list.push(`${key}=${object[key]}`); }); return list.join('&'); } exports.toUrlParams = toUrlParams;