import { LexoRank } from "lexorank";

type LexorankSortable = {
    lexorank: string;
};

export function compareByLexorank<T extends LexorankSortable>(
    a: T,
    b: T
): -1 | 1 | 0 {
    if (a.lexorank < b.lexorank) {
        return -1;
    }
    if (a.lexorank > b.lexorank) {
        return 1;
    }
    return 0;
}

export function sortByLexorank<T extends LexorankSortable>(items: T[]): T[] {
    return items.sort(compareByLexorank);
}

export function getMaxByLexorank<T extends LexorankSortable>(
    items: T[]
): T | null {
    return items.reduce(
        (max, item) => (!max || item.lexorank > max.lexorank ? item : max),
        null as T | null
    );
}

export function getNewLexorank(
    left?: LexoRank | null,
    right?: LexoRank | null
): LexoRank {
    if (right) {
        if (left) return left?.between(right);
        return right.between(LexoRank.min());
    }
    if (left) {
        return left.between(LexoRank.max());
    }
    return LexoRank.middle();
}
