/**
 *
 * @param {Map<*, TypeEditor>} registry
 * @param {*} value
 * @returns {TypeEditor|void}
 */
export function findNearestRegisteredType(registry, value) {
    const path = [];

    let editor;
    let t = value;
    do {

        if (t === undefined || t === null) {
            return;
        }


        editor = registry.get(t);

        if (editor !== undefined) {
            return editor;
        }

        if (typeof t === "function" && t !== Function) {
            // t is a class, classes have Function prototype, this is confusing, but we want to skip going to function class in this case
            t = t.prototype;
            continue;
        }

        if (t.constructor !== undefined) {

            editor = registry.get(t.constructor);

            if (editor !== undefined) {
                return editor;
            }
        }

        const proto = Object.getPrototypeOf(t);

        if (proto === undefined || proto === null) {
            return;
        }


        const ctor = proto;

        t = ctor;

        if (path.includes(t)) {
            // circular dependency detected
            return;
        }

        path.push(t);

    } while (true);
}
