import { stringify } from '../../lib/util.js';
export function merge(data, commit) {
    if (commit === undefined) {
        return data;
    }
    else if (commit === null) {
        return null;
    }
    else {
        const output = new Map(Object.entries(data));
        if (is_object(data) && is_object(commit)) {
            Object.keys(commit).forEach((key) => {
                if (commit[key] === null) {
                    output.delete(key);
                }
                else if (is_object(commit[key])) {
                    if (!(key in data)) {
                        output.set(key, commit[key]);
                    }
                    else {
                        const val = merge(data[key], commit[key]);
                        if (val === null) {
                            output.delete(key);
                        }
                        else {
                            output.set(key, val);
                        }
                    }
                }
                else if (Array.isArray(commit[key])) {
                    const arr = commit[key];
                    const dat = (data[key] ?? [])
                        .map((e) => stringify(e));
                    const set = new Set(dat);
                    const add = arr.filter((e) => {
                        return e !== null && !set.has(stringify(e));
                    });
                    const val = (data[key] || [])
                        .filter((_, idx) => arr[idx] !== null)
                        .concat(add);
                    output.set(key, val);
                }
                else {
                    output.set(key, commit[key]);
                }
            });
        }
        return Object.fromEntries(output);
    }
}
function is_object(item) {
    return (item !== null &&
        typeof item === 'object' &&
        !Array.isArray(item));
}
