Typescript Find Common Prefix

Date: 2024-01-28
type MyDictionary = { [key: string]: string[] };

export function groupAndFindLargest(names: string[]) {
    if (names.length <= 1) {
        return [];
    }

    // Group names by their first two characters
    const groupedNames = names.reduce((groups, name) => {
        const prefix = name.slice(0, 2);
        if (!groups[prefix]) {
            groups[prefix] = [];
        }
        groups[prefix].push(name);
        return groups;
    }, {} as MyDictionary);

    // Find the largest group
    return Object.values(groupedNames).reduce((largest, group) => {
        return group.length > largest.length ? group : largest;
    }, []);
}

export function findCommonPrefix(names: string[]) {
    if (names.length <= 1) {
        return '';
    }

    // Sort the names to ensure that names with the same prefix are adjacent
    const sortedNames = [...names].sort();

    // Take the first and last elements (lexicographically) as reference points
    const firstName = sortedNames[0];
    const lastName = sortedNames[sortedNames.length - 1];

    // Find the common prefix between the first and last name
    let commonPrefix = '';
    for (let i = 0; i < firstName.length; i++) {
        if (firstName[i] !== lastName[i]) {
            break;
        }
        commonPrefix += firstName[i];
    }
    return commonPrefix;
}

export function removePrefix(name: string, prefix: string) {
    if (name.startsWith(prefix) && name.length > prefix.length)
        return name.slice(prefix.length);
    return name;
}
82130cookie-checkTypescript Find Common Prefix