Typescript / javascript full outer join

Date: 2021-01-04
const filterUnique = () => {
    const keys = new Set<string>();
    return (key: string) => !keys.has(key) ? keys.add(key) || true : false;
};

function* fullOuterJoin<L, R, S>(left: L[], right: R[], keyFn: (a: any) => string, selectFn: (left: L, right: R, key: string) => S) {
    const leftLookup: { [key: string]: L } = {};
    const rightLookup: { [key: string]: R } = {};
    left.forEach(x => leftLookup[keyFn(x)] = x);
    right.forEach(x => rightLookup[keyFn(x)] = x);
    const unique = filterUnique();
    const keys = [...left.map(x => keyFn(x)), ...right.map(x => keyFn(x))].filter(unique);
    for (const key of keys) {
        const l = leftLookup[key];
        const r = rightLookup[key];
        yield selectFn(l, r, key);
    }
};

const left = [1, 2, 3, 4];
const right = [3, 4, 5, 6];

for (const item of fullOuterJoin(left, right, (a) => a, (l: number, r: number, k: string) => ({ l, r }))) {
    console.log('item', item);
}

const flattenObject = (obj: object): any => {
    const result = {};
    for (const [k, v] of Object.entries(obj)) {
        if (typeof v === "object" && v) {
            for (const [x, y] of Object.entries(flattenObject(v))) {
                result[k + "." + x] = y;
            }
            continue;
        }
        result[k] = v;
    }
    return result;
};


44120cookie-checkTypescript / javascript full outer join