UNPKG

typeparse

Version:

Runtime object transformation, parsing and validation with inferred static TypeScript typing.

35 lines (34 loc) 1.53 kB
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Kenneth Herrera. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.get = void 0; const INDEX_SYNTAX_RE = /^\[(-?\d+)\]$|^((?!\\\[).+)|\\(.+)$/; function accessPath(input, path) { var _a, _b; const key = path.shift(); if (key === undefined) return input; if (!input) return undefined; if (typeof input !== "object") return undefined; const match = INDEX_SYNTAX_RE.exec(key); const arrayKey = (match === null || match === void 0 ? void 0 : match[1]) ? Number.parseInt(match[1]) : undefined; if (arrayKey !== undefined) { if (!Array.isArray(input)) return undefined; if (arrayKey < 0) return accessPath(input[input.length + arrayKey], path); return accessPath(input[arrayKey], path); } return accessPath(input[(_b = (_a = match === null || match === void 0 ? void 0 : match[2]) !== null && _a !== void 0 ? _a : match === null || match === void 0 ? void 0 : match[3]) !== null && _b !== void 0 ? _b : ""], path); } function get(input, path) { if (path === undefined) return input; return accessPath(input, path.split(".")); } exports.get = get;