UNPKG

dtsgenerator

Version:

TypeScript d.ts file generator for JSON Schema file

72 lines (71 loc) 1.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tilde = exports.parse = exports.set = exports.get = void 0; function get(obj, path, isCreateOnNotExists = false) { if (path.length === 0) { return obj; } let o = obj; const lastKey = path[path.length - 1]; for (let i = 0; i < path.length - 1; i++) { const key = path[i]; let next = o[key]; if (next == null) { if (isCreateOnNotExists) { next = {}; o[key] = next; } else { return undefined; } } o = next; } return o[lastKey]; } exports.get = get; function set(obj, path, value) { if (path.length === 0) { return; } let o = obj; const lastKey = path[path.length - 1]; for (let i = 0; i < path.length - 1; i++) { const key = path[i]; let next = o[key]; if (next == null) { next = {}; o[key] = next; } o = next; } o[lastKey] = value; } exports.set = set; function parse(s) { if (s.startsWith('#')) { s = s.substring(1); } const path = s.split('/'); if (path.shift() !== '') { throw new Error('Invalid JSON-Pointer format: ' + s); } return path.map((key) => untilde(key)); } exports.parse = parse; function untilde(key) { return key.replace(/~(0|1)/g, (match) => { switch (match) { case '~0': return '~'; case '~1': return '/'; default: throw new Error('Unsupported tilded number.'); } }); } function tilde(key) { return key.replace(/~/, '~0').replace(/\//g, '~1'); } exports.tilde = tilde;