Skip to content

Instantly share code, notes, and snippets.

@jherr
Created April 17, 2021 20:57
Show Gist options
  • Save jherr/cd442b46070b39e99dd8bedc9eecff5c to your computer and use it in GitHub Desktop.
Save jherr/cd442b46070b39e99dd8bedc9eecff5c to your computer and use it in GitHub Desktop.
Challenge #1
[
{ "name": "Atreides", "planets": "Calladan" },
{ "name": "Corrino", "planets": ["Kaitan", "Salusa Secundus"] },
{ "name": "Harkonnen", "planets": ["Giedi Prime", "Arrakis"] }
]
interface House {
...
}
interface HouseWithID {
...
}
function findHouses(houses: string): HouseWithID[];
function findHouses(
houses: string,
filter: (house: House) => boolean
): HouseWithID[];
function findHouses(houses: House[]): HouseWithID[];
function findHouses(
houses: House[],
filter: (house: House) => boolean
): HouseWithID[];
console.log(
findHouses(JSON.stringify(houses), ({ name }) => name === "Atreides")
);
console.log(findHouses(houses, ({ name }) => name === "Harkonnen"));
@ElMehdi-l
Copy link

import houses from "./houses.json";

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

interface HouseWithID {
  id: number;
  house: House;
}

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

function findHouses(houses: string): HouseWithID[];
function findHouses(houses: string, filter: FilterFunc): HouseWithID[];
function findHouses(houses: House[]): HouseWithID[];
function findHouses(houses: House[], filter: FilterFunc): HouseWithID[];

function findHouses(houses: unknown, filter?: unknown): HouseWithID[] {
  let housesWithID: HouseWithID[] = (
    typeof houses === "string" ? JSON.parse(houses) : houses
  ).map((house: House, index: number) => ({
    house,
    id: index + 1,
  }));

  if (typeof filter === "function") {
    housesWithID = housesWithID.filter((house: HouseWithID) =>
      (filter as FilterFunc)(house.house)
    );
  }

  return housesWithID;
}

console.log(findHouses(JSON.stringify(houses)));

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

console.log(findHouses(houses, ({ name }) => name === "Harkonnen"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment