Skip to content
loading...

re: [JavaScript] - How to craft intuitive and self-documenting code VIEW POST

FULL DISCUSSION
 

Or, alternatively ...


const formattedHotels = (byCountry, hotelsAry) =>
  hotelsAry.reduce((selectedHotels, hotel) =>
    (hotel.country.toLowerCase() === byCountry.toLowerCase())
      ? [
          ...selectedHotels,
          {...hotel,
              phone: `(${hotel.phone.slice(0,3)}) ${hotel.phone.slice(3,6)} ${hotel.phone.slice(6)}`}
        ]
      : selectedHotels
  , []);

const usHotels = formattedHotels('usa', hotels);
console.log(usHotels);

This will probably make you squint, but it's short and sweet!

[edited: 16JUNE]

...

On reflection though, maybe, as you are talking about decomposing code as much as possible; then this might be a better solution...


// propCmp => compare the value of a property of an object using a predicate function.
// propCmp : (fn, String) -> Object -> Boolean|undefined
const propCmp = (pred, key) => obj => (key in obj) ? (pred(obj[key]) ? true : false ) : undefined

// a predicate function to determine if the value of a property is === 'usa'
const isUSA = val => (val.toLowerCase() === 'usa')

// use propCmp to see if country is === 'usa|USA'
const countryEqUSA = propCmp(isUSA, 'country')

// function to format the hotel phone no.
const formatHot = hotl => ({...hotl, phone: `(${hotl.phone.slice(0,3)}) ${hotl.phone.slice(3,6)} ${hotl.phone.slice(6)}`})

// a function to format selected hotels.
const formatHotels = (byCountry, htelsAry) =>
  htelsAry
    .filter(byCountry)
    .map(formatHot)

console.log(formatHotels(countryEqUSA, hotels))


Hope one of these two methods clicks with you.

Keep up the fp posts.

Cheers!

code of conduct - report abuse