"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepCopyMapTree = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
/**
 * Returns a deep copy of the given {@link MapTree}.
 * @privateRemarks This is implemented iteratively (rather than recursively, which is much simpler)
 * to avoid the possibility of a stack overflow for very deep trees.
 */
function deepCopyMapTree(mapTree) {
    function create(child, fields) {
        return {
            type: child.type,
            ...(child.value === undefined ? {} : { value: child.value }),
            fields,
        };
    }
    const rootFields = new Map();
    const nexts = [[rootFields, mapTree.fields]];
    for (let next = nexts.pop(); next !== undefined; next = nexts.pop()) {
        const [fields, sourceFields] = next;
        for (const [key, field] of sourceFields) {
            (0, internal_1.assert)(field.length > 0, 0xbb3 /* invalid map tree: empty field */);
            if (field.length > 0) {
                const newField = [];
                for (const child of field) {
                    const childClone = create(child, new Map());
                    newField.push(childClone);
                    nexts.push([childClone.fields, child.fields]);
                }
                fields.set(key, newField);
            }
        }
    }
    return create(mapTree, rootFields);
}
exports.deepCopyMapTree = deepCopyMapTree;
//# sourceMappingURL=mapTree.js.map