-
-
Save gtkatakura/ae52a005e211ce8076eb45aed8b8a807 to your computer and use it in GitHub Desktop.
lodash/fp + mapValues + toResponseBy = toMovie
This file contains 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
import _ from 'lodash/fp' | |
const response = { | |
"Title": "Pulp Fiction", | |
"Year": "1994", | |
"Rated": "R", | |
"Released": "14 Oct 1994", | |
"Runtime": "154 min", | |
"Genre": "Crime, Drama", | |
"Director": "Quentin Tarantino", | |
"Writer": "Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino", | |
"Actors": "Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta", | |
"Plot": "The lives of two mob hitmen, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption.", | |
"Language": "English, Spanish, French", | |
"Country": "USA", | |
"Awards": "Won 1 Oscar. Another 60 wins & 68 nominations.", | |
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMTA5OTAzMl5BMl5BanBnXkFtZTgwNjA5MDc3NjE@._V1_SX300.jpg", | |
"Ratings": [ | |
{ | |
"Source": "Internet Movie Database", | |
"Value": "8.9/10" | |
}, | |
{ | |
"Source": "Rotten Tomatoes", | |
"Value": "94%" | |
}, | |
{ | |
"Source": "Metacritic", | |
"Value": "94/100" | |
} | |
], | |
"Metascore": "94", | |
"imdbRating": "8.9", | |
"imdbVotes": "1,501,400", | |
"imdbID": "tt0110912", | |
"Type": "movie", | |
"DVD": "19 May 1998", | |
"BoxOffice": "N/A", | |
"Production": "Miramax Films", | |
"Website": "N/A", | |
"Response": "True", | |
} | |
const mapValues = transformation => ( | |
_.pipe( | |
_.toPairs, | |
_.map(([key, value]) => [key, transformation(value, key)]), | |
_.fromPairs, | |
) | |
) | |
const toResponseBy = ({ mappings, keys }) => { | |
const allKeys = [..._.keys(mappings), ...keys]; | |
return _.flow( | |
_.mapKeys(_.camelCase), | |
_.pick(allKeys), | |
mapValues((value, key) => { | |
const transformation = mappings[key] || _.identity; | |
return transformation(value); | |
}), | |
); | |
}; | |
const toMovie = toResponseBy({ | |
mappings: { | |
year: Number, | |
imdbRating: Number, | |
actors: _.split(', '), | |
genre: _.split(', '), | |
}, | |
keys: [ | |
'title', | |
'director', | |
'type', | |
], | |
}); | |
console.log(toMovie(response)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment