/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@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.
 */
export 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) {
            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);
}
//# sourceMappingURL=mapTree.js.map