Created
April 17, 2021 20:57
-
-
Save jherr/cd442b46070b39e99dd8bedc9eecff5c to your computer and use it in GitHub Desktop.
Challenge #1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ "name": "Atreides", "planets": "Calladan" }, | |
{ "name": "Corrino", "planets": ["Kaitan", "Salusa Secundus"] }, | |
{ "name": "Harkonnen", "planets": ["Giedi Prime", "Arrakis"] } | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); |
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
Hi @jherr ,
Thanks for your series.
Here's my solution :