UNPKG

@azure-tools/codegen

Version:
83 lines (80 loc) 3.13 kB
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.Initializer = void 0; const empty = new Set(); function applyTo(source, target, exclusions, cache = new Set()) { if (cache.has(source)) { throw new Error("Circular refrenced models are not permitted in apply() initializers."); } for (const i of Object.keys(source !== null && source !== void 0 ? source : {})) { if (exclusions.has(i)) { continue; } switch (typeof source[i]) { case "object": // merge objects if (source[i] != null && source[i] != undefined && typeof target[i] === "object") { cache.add(source); try { applyTo(source[i], target[i], exclusions, cache); } catch (E) { // eslint-disable-next-line no-console console.error(` in property: ${i} `); throw E; } cache.delete(source); continue; } // otherwise, just use that object. target[i] = source[i]; continue; /* bad idea? : this recursively cloned the contents of the intializer but this has the effect of breaking referencs where I wanted them. // copy toarray if (Array.isArray(source[i])) { cache.add(source); applyTo(source[i], target[i] = [], cache); cache.delete(source); continue; } // otherwise, copy into an empty object cache.add(source); applyTo(source[i], target[i] = {}, cache); cache.delete(source); continue; */ default: // everything else just replace. target[i] = source[i]; continue; } } } /** inheriting from Initializer adds an apply<T> method to the class, allowing you to accept an object initalizer, and applying it to the class in the constructor. */ class Initializer { apply(...initializer) { for (const each of initializer) { applyTo(each, this, empty); } } applyWithExclusions(exclusions, ...initializer) { const filter = new Set(exclusions); for (const each of initializer) { applyTo(each, this, filter); } } applyTo($this, ...initializer) { for (const each of initializer) { applyTo(each, $this, empty); } } } exports.Initializer = Initializer; //# sourceMappingURL=initializer.js.map