Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement