Ramda on native Js

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 as R.length(R.filter(someArray)) which is the same as JS’ native OO chaining interface of someArray.filter().length.
  • assoc clones an object and adds/overwrites a property on it - R.assoc('count', phoneCount(phone.id), phone) clones the phone object and adds a property called count with a value of whatever integer phoneCount(phone.id) returns; it is the same as Object.assign({}, phone, {count: phoneCount(phone.id)}) but in chainable functional form.
2 Likes