How does this code look without Ramda on native Js (es6) ?
there’s some context missing (what the data looks like, what getPhoneById
is) so can’t tell if this is exactly correct, but from what’s provided:
export const getBasketPhonesWithCount = state => {
const phoneCount = id =>
state.basket.filter(({basketId}) => basketId === id).length;
const phoneWithCount = phone =>
Object.assign({}, phone, {count: phoneCount(phone.id)});
const uniqueIds = [...new Set(state.basket)];
return uniqueIds.map(({id}) => getPhoneById(state, id)).map(phoneWithCount);
}
Using function declarations rather than function expressions with arrow syntax:
function getBasketPhonesWithCount (state) {
function phoneCount (id) {
return state.basket.filter(function (b) {
return b.basketId === id
}).length;
}
function phoneWithCount (phone) {
return Object.assign({}, phone, {count: phoneCount(phone.id)}
}
function uniqueIds () {
return Array.from(new Set(state.basket));
}
return uniqueIds.map(function (u) {
return getPhoneById(state, u.id)).map(phoneWithCount);
}
}
export getBasketPhonesWithCount;
Notes:
- Ramda curries everything automatically (every function takes one and only one argument).
-
compose
applies the functions given to it in reverse order:R.compose(R.length, R.filter)(someArray)
is the same asR.length(R.filter(someArray))
which is the same as JS’ native OO chaining interface ofsomeArray.filter().length
. -
assoc
clones an object and adds/overwrites a property on it -R.assoc('count', phoneCount(phone.id), phone)
clones thephone
object and adds a property calledcount
with a value of whatever integerphoneCount(phone.id)
returns; it is the same asObject.assign({}, phone, {count: phoneCount(phone.id)})
but in chainable functional form.
2 Likes