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
    })
}

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 =>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.