Skip to content

Instantly share code, notes, and snippets.

@iboss-ptk
Created July 4, 2019 03:08
Show Gist options
  • Select an option

  • Save iboss-ptk/499d7c02ba3bd35225e0098405bb7a23 to your computer and use it in GitHub Desktop.

Select an option

Save iboss-ptk/499d7c02ba3bd35225e0098405bb7a23 to your computer and use it in GitHub Desktop.
type Game = {
name: string
rating: number
}
const gameList: Game[] = [
{ name: 'call of duty', rating: 4.0 },
{ name: 'assasin creed', rating: 6.4 },
{ name: 'mario', rating: 10.2 },
]
// 1. returns list of name from list of game
const names = (games: Game[]): string[] =>
games.map(game => game.name)
// 2. returns list of string that has format `<name> [<rating>]`
// eg. `call of duty [7.4]`
const formatGames = (games: Game[]): string[] =>
games.map(({ name, rating }) => `${name} [${rating}]`)
// 3. get sum of all the ratings in list of game
const totalRatingsOf = (games: Game[]): number =>
games
.map(game => game.rating)
.reduce((a, b) => a + b, 0)
// 4. get average of all the ratings in list of game
const averageRatingsOf = (games: Game[]): number =>
totalRatingsOf(games) / games.length
// ----
const gamesWithName = (name: string, games: Game[]): Game[] =>
games.filter(game => game.name === name)
// 5. get total rating by names from list of game
const ratingByName = (name: string, games: Game[]): number =>
totalRatingsOf(gamesWithName(name, games))
// 6. get total rating by names from list of game
const averageRatingsByName = (name: string, games: Game[]): number =>
averageRatingsOf(gamesWithName(name, games))
// ---
const updateGameRating = (update: (rating: number) => number) => (game: Game) => ({
...game,
rating: update(game.rating)
})
// 7. increase rating for all games
const increaseRatingBy = (inc: number, games: Game[]): Game[] =>
games
.map(updateGameRating(rating => rating + inc))
// 8. decrease rating for game with specific name
const decreaseRatingBy = (
dec: number,
name: string,
games: Game[],
): Game[] =>
gamesWithName(name, games)
.map(updateGameRating(rating => rating - dec))
// 9. returns game if the name exist else returns undefined
const findByName = (name: string, games: Game[]): Game =>
games.find(game => game.name === name)
// games.reduce((found, game) =>
// found
// ? found
// : game.name === name
// ? game
// : undefined
// , undefined)
console.log(findByName('call of duty', gameList))
// 10. decrease rating for game that has name in the list
const decreaseRatingForNames = (
dec: number,
names: string[],
games: Game[],
): Game[] =>
games
.filter(game => names.includes(game.name))
.map(updateGameRating(rating => rating - dec))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment