Skip to content

Instantly share code, notes, and snippets.

@aungmyatmoethegreat
Created January 14, 2023 22:02
Show Gist options
  • Save aungmyatmoethegreat/3de41ccf4f296a92aa9b382b0fbfc49e to your computer and use it in GitHub Desktop.
Save aungmyatmoethegreat/3de41ccf4f296a92aa9b382b0fbfc49e to your computer and use it in GitHub Desktop.
Typescript function overloading solution

Challenge

https://gist.github.com/jherr/cd442b46070b39e99dd8bedc9eecff5c

There are too many complicated answers at there. How to use condition effectively?

Solution

The real solution is KISS

interface House {
    name: string;
    planets: string | string[];
}

interface HouseWithID extends House {
    id: number;
}

type TFilterFn = (house: House) => boolean;

function findHouses(houses: string): HouseWithID[];
function findHouses(
    houses: string,
    filter: TFiler
): HouseWithID[];
function findHouses(houses: House[]): HouseWithID[];
function findHouses(
    houses: House[],
    filter: TFilterFn
): HouseWithID[];
function findHouses(arg1: unknown, filter?: TFilterFn): HouseWithID[] {
    const houses = Array.isArray(arg1) ? arg1 : JSON.parse(arg1);

    const housesWithID = houses.map((house, index) => ({
        ...house,
        id: index,
    }));
    return filter ? housesWithID.filter(filter) : housesWithID;
}


const houses = [
    {"name": "Atreides", "planets": "Calladan"},
    {"name": "Corrino", "planets": ["Kaitan", "Salusa Secundus"]},
    {"name": "Harkonnen", "planets": ["Giedi Prime", "Arrakis"]}
]


console.log(
    findHouses(JSON.stringify(houses), ({name}) => name === "Atreides")
);

console.log(findHouses(houses, ({name}) => name === "Harkonnen"));
console.log(findHouses(houses));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment