3

Example this code I wrote doesn't seem as readable as it could be:

function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Dany M
  • 113
  • 2
  • 2
  • 9

3 Answers3

1

Seems okay to me to be honest. What you could do is replace the "50" with a variable in your js file.

var MESSAGE_MAX_LENGTH= 50;

And re position a bit the way you address the function

function getShortMessages(messages) {
    return messages
        .filter( (messageObject) => { 
            return messageObject.message.length < MESSAGE_MAX_LENGTH 
        })
        .map( (messageObject) => {
            return messageObject.message 
        });
}

Also I find that when addressing an array of messages and running through the filter function, it is better to not call the object messages but item or messageObject

moreover, object in the map function is a bit ominous, call it messageObject again for example so you know what you are using specifically

Tikkes
  • 4,599
  • 4
  • 36
  • 62
1

in ES 6 you can use shortcuts, like this:

function getShortMessages(messages) {
    return messages.filter( messages => messages.message.length < 50).map( object => object.message )
}

Its depend on you which one is readable. In one line you dont need to use {} nor return and if you use array function, with 1 parameter you also dont need (messages) => , you can use only messages =>

0

function getShortMessages(messages) {
  return messages.filter(message => message.message.length < 50)
    .map(message => message.message)
}
Mikalai
  • 1,515
  • 8
  • 21