¡No te pierdas ninguna publicación! Suscríbete a The Softtek Blog
const letters = ['a', 'b', 'c', 'd']
R.map(R.toUpper)(letters)
// ['A', 'B', 'C', 'D']
R.filter(n => n % 2 === 0)([1, 2, 3, 4, 5, 6, 7, 8, 9])
// [2, 4, 6, 8]
R.reject(n => n % 2 === 0)([1, 2, 3, 4, 5, 6, 7, 8, 9])
// [1, 3, 5, 7, 9]
R.reduce(R.add, 0)([1, 2, 3, 4, 5, 6, 7, 8, 9])
// 45
R.reduce(R.concat, '')(['a', 1, 'b', 2, 'c', 3])
// a1b2c3
R.invertObj(['one', 'two', 'three'])
// { 'one': 0, 'two': 1, 'three': 2 }
R.pluck('name')([
{ name: 'Axl Rose', instrument: 'vocals' },
{ name: 'Slash', instrument: 'guitar' },
{ name: 'Izzy Stradlin', instrument: 'guitar' },
{ name: 'Steven Adler', instrument: 'drums' },
{ name: 'Duff McKagan', instrument: 'bass guitar' }
])
// [ 'Axl Rose', 'Slash', 'Izzy Stradlin', 'Steven Adler', 'Duff McKagan']
const unsorted = [2, 1, 5, 4, 3]
R.sort(R.gt, unsorted)
// [1, 2, 3, 4, 5]
R.sort(R.lt, unsorted)
// [5, 4, 3, 2, 1]
R.reverse(unsorted)
// [3, 4, 5, 1, 2]
const gunsAndRoses = {
yearsActive: '1985-present',
origin: 'Los Angeles',
members: {
/*...*/
}
}
const originLens = R.lensProp('origin')
R.view(originLens, gunsAndRoses)
// 'Los Angeles'
R.set(originLens, 'Los Angeles, California', gunsAndRoses)
// {... 'origin': 'Los Angeles, California' ...}
R.over(originLens, R.replace('Los Angeles', 'LA'), gunsAndRoses)
// {... 'origin': 'LA' ...}
const theWho = {
yearsActive: '1964-1982, 1989, 1996-present',
origin: 'London',
members: {
singer: 'Roger Daltrey',
guitarist: 'Pete Townshend',
bassGuitarist: 'John Entwistle',
drummer: 'Keith Moon'
},
followers: 787989,
website: null,
active: false
}
const bandUpdates = {
bandName: 'The Who', // No existe la key, no aplica
members: {
drummer: R.always('Kenney Jones') // Es una función, aplica la transformación
},
followers: R.add(1500),
website: R.always('theWho.com'),
origin: 'London, UK', // No es una función, no aplica
active: R.not
}
R.evolve(bandUpdates, theWho)
// {
// yearsActive: '1964-1982, 1989, 1996-present',
// origin: 'London',
// members: {
// singer: 'Roger Daltrey',
// guitarist: 'Pete Townshend',
// bassGuitarist: 'John Entwistle',
// drummer: 'Kenney Jones'
// },
// followers: 789489,
// website: 'theWho.com',
// active: true
// }
const theWho = {
yearsActive: '1964-1982, 1989, 1996-present',
origin: 'London',
demonym: 'British',
members: {
singer: 'Roger Daltrey',
guitarist: 'Pete Townshend',
bassGuitarist: 'John Entwistle',
drummer: 'Keith Moon'
},
followers: 787989,
website: null,
active: false
}
const acdc = {
bandName: 'AC/DC'
yearsActive: '1973-present',
origin: 'Sydney',
demonym: 'Australian',
members: {
singer: 'Brian Johnson',
guitarist: 'Angus Young',
bassGuitarist: 'Stevie Young',
drummer: 'Chris Slade'
}
}
const pickSinger = R.path(['members', 'singer'])
const pickDemonym = R.prop('demonym')
const pickBandName = R.propOr('', 'bandName')
const processBand = (singer, demonym, bandName) => `${singer} is the lead singer of the ${demonym} rock band ${bandName}`
R.converge(processBand, [pickSinger, pickDemonym, pickBandName])(acdc)
// Brian Johnson is the lead singer of the Australian rock band AC/DC
R.converge(processBand, [pickSinger, pickDemonym, pickBandName])(theWho)
// Roger Daltrey is the lead singer of the British rock band
const threeArgumentsFn = R.binary(R.flip((a, b, c) => `${a} ${b} ${c}`))
threeArgumentsFn('a', 'b', 'c')
// b a undefined
const pickMetallicaProp = R.path(R.__, metallica)
pickMetallicaProp(['members', 'singer'])
// James Hetfield
pickMetallicaProp(['origin'])
// Los Angeles
const insertInList = R.insert(R.__, R.__, [1, 2, 3, 4])
insertInList(1, 'Value at index 1')
// [1, 'Value at index 1', 3, 4]
insertInList(4)('Value at end')
// [1, 2, 3, 'Value at end']
const trace = R.tap(console.log)
const doSomeStuffWithBand = R.compose(
trace, R.concat('Mr. '),
trace, R.head,
trace, R.reverse,
trace, R.split(' '),
trace, R.path(['members', 'drummer'])
) // Recordemos que compose va de derecha a izquierda
doSomeStuffWithBand(ledZeppelin)
// 'Mr. Bonham'
John Bonham
['John','Bonham']
['Bonham','John']
Bonham
Mr. Bonham
John Bonham
['John','Bonham']
['Bonham','John']
Bonham
Mr. Bonham
let count = 0
const factorial = R.memoize(n => {
count++
return R.product(R.range(1, n + 1))
})
const factorialize = () => {
console.time('factorialize')
factorial(20000000)
console.timeEnd('factorialize')
}
factorialize() // factorialize: 790.96484375ms
factorialize() // factorialize: 0.305908203125ms
factorialize() // factorialize: 0.044677734375ms
factorialize() // factorialize: 0.037841796875ms
factorialize() // factorialize: 0.06396484375ms
count // 1
fetch('https://api.spotify.com/v1/artists/5M52tdBnJaKSvOpJGz8mfZ')
.then(R.invoker(0, 'json'))
.then(R.pickAll(['name', 'popularity', 'type']))
// { 'name': 'Black Sabbath', 'popularity': 70, 'type': 'artist' }
const blackSabbath = { name: 'Black Sabbath', category: 'Heavy Metal', tour: 'The End', ticketPrice: 140 }
const greenDay = { name: 'Green Day', category: 'Punk Rock', tour: '99 Revolutions Tour', ticketPrice: 80 }
const acdc = { name: 'AC/DC', category: 'Hard Rock', tour: 'Rock or Bust World Tour', ticketPrice: 200 }
const rollingStones = { name: 'The Rolling Stones', category: 'Rock', tour: '', ticketPrice: 130 }
const tours = [ blackSabbath, greenDay, acdc, rollingStones ]
const assistanceChooser = R.cond([
[ R.propEq('category', 'Rock'), band => `I'll assit to the ${band.name} concert` ], // Es un concierto de categoría Rock?
[ R.propSatisfies(R.lt(R.__, 100), 'ticketPrice'), R.always('As it's cheap, I'll assist to the concert') ], // Es un concierto de menos de 100?
[ R.T, band => `I won't assist to ${band.name} concert`] // Default case
])
assistanceChooser(greenDay)
// 'As it's cheap, I'll assist to the concert'
assistanceChooser(rollingStones)
// 'I'll assit to the The Rolling Stones concert'
assistanceChooser(blackSabbath)
// 'I won't assist to Black Sabbath concert'
const purchaseTicket = R.when(
R.allPass([
R.propEq('name', 'Black Sabbath'),
R.propSatisfies(R.lt(R.__, 150), 'ticketPrice')
]),
R.assoc('ticketPurchased', true)
)
purchaseTicket(rollingStones)
// No aplica ninguna transformación, no cumple ninguna de las condiciones de allPass
purchaseTicket(acdc)
// No aplica ninguna transformación, el precio es superior a 150
purchaseTicket(blackSabbath)
// Cumple todas las condiciones, añade ticketPurchased al objeto resultante
// {'category': 'Heavy Metal', 'name': 'Black Sabbath', 'ticketPrice': 140, 'ticketPurchased': true, 'tour': 'The End'}
R.isEmpty(tours) // false, no esta vacio
R.not(R.isEmpty(tours)) // true, no esta vacio
R.not(R.isEmpty([])) // false, esta vacio
R.is(Number, greenDay) // false
R.is(Object, acdc) // true
import { map, compose, lensProp, over, propEq, T, cond, identity, match } from 'ramda'
const blackSabbath = { name: 'Black Sabbath', category: 'Heavy Metal', price: 140, purchased: 9376, total: 20000 }
const defLeppard = { name: 'Def Leppard', category: 'Rock', price: 125, purchased: 8423, total: 15000 }
const greenDay = { name: 'Green Day', category: 'Punk Rock', price: 80, purchased: 1425, total: 15000 }
const acdc = { name: 'AC/DC', category: 'Hard Rock', price: 200, purchased: 24765, total: 25000 }
const rollingStones = { name: 'The Rolling Stones', category: 'Rock', price: 130, purchased: 5671, total: 25000 }
const nextConcerts = [greenDay, defLeppard, blackSabbath, acdc, rollingStones]
//Lenses
const priceLens = lensProp('price')
const radioLens = lensProp('radio')
const purchasedLens = lensProp('purchased')
//Discounts
const calculateDiscount = perc => amt => amt - amt * (perc / 100)
const discount = d => over(priceLens, calculateDiscount(d))
const fivePercentDiscount = discount(5)
const tenPercentDiscount = discount(10)
const twentyPercentDiscount = discount(20)
//Other transformations not related with the price
const includeRadioAds = over(radioLens, T)
const partnershipRadioTickets = over(purchasedLens, add(300))
//Campaings predicates
const isAlmostFull = ({ total, purchased }) => total - purchased < 1000
const isGreenDay = propEq('name', 'Green Day')
const containsRock = compose(not, isEmpty, match(/(rock)/gi))
const hasRockCategory = propSatisfies(containsRock, 'category')
//Special campaings
const lastTicketsCampaing = compose(twentyPercentDiscount, includeRadioAds)
const radioRockCampaing = compose(fivePercentDiscount, includeRadioAds, partnershipRadioTickets)
const greenDayCampaing = tenPercentDiscount
//Map campaings with its transformations
const configureCampaings = cond([
[isAlmostFull, lastTicketsCampaing],
[isGreenDay, greenDayCampaing],
[hasRockCategory, radioRockCampaing],
[T, identity]
])
//Apply the campaings to all the concerts
const applyCampaings = map(configureCampaings)
//Run it!
applyCampaings(nextConcerts)
[
{ category: 'Punk Rock', name: 'Green Day', price: 72, purchased: 1425, total: 15000 },
{ category: 'Rock' name: 'Def Leppard' price: 118.75 purchased: 8723 radio: true total: 15000 },
{ category: 'Heavy Metal' name: 'Black Sabbath' price: 140 purchased: 9376 total: 20000 },
{ category: 'Hard Rock' name: 'AC/DC' price: 160 purchased: 24765 radio: true total: 25000 },
{ category: 'Rock' name: 'The Rolling Stones' price: 123.5 purchased: 5971 radio: true total: 25000 }
]