2

What is the best way to style for better readability, nested lambda expressions such as:

movieLists.forEach(movie => movie.videos.forEach(
                     video => allVideoIdsInMovieLists.push(video.id)));

Any Styling Guide or best practices for Lambda expressions.

3
  • What is issue with pattern at Question? Commented Jul 15, 2017 at 4:38
  • Wanted to know is there any style guide for such patterns, as for more than 1 level deep nested structure the code might become difficult to read. Commented Jul 15, 2017 at 4:46
  • 1
    If there is no issue with JavaScript at Question the inquiry is based on preference and opinion, which only you can decide upon. The expected result could also be returned using .map() and .concat() let allVideoIdsInMovieLists = [].concat(...movieLists.map(({videos}) => videos.map(({id}) => id))) or .map() and .pop() let allVideoIdsInMovieLists = movieLists.map(({videos}) => videos.map(({id}) => id)).pop() Commented Jul 15, 2017 at 4:48

1 Answer 1

6

There's nothing wrong with your code. However, some people like to follow the style of defining little functions, which among other benefits, can make the code more readable by introducing better names.

const pushVideos = videos => videos.forEach(pushVideo);
const pushVideo  = video  => allVideoIdsInMovieLists.push(video.id);
const pushMovie  = movie  => pushVideos(movie.videos);

movieLists.forEach(pushMovie);

However, you have a couple alternatives for structuring this code. First would be one big concat:

allVideosInMovieLists = [].concat(...movieLists.map(movie => movie.videos.map(video => video.id)));

It would also be reasonable to write a good-old for loop:

for (movie of movieLists) 
  for (video of movie.videos) 
    allVideoIdsInMovieList.push(video.id);

There are those who would say this is more readable.

Going back to your original code, deconstructing the arguments lists might make it a bit more readable:

movieLists.forEach(({videos}) => 
  videos.forEach(({id}) => 
    allVideoIdsInMovieLists.push(id)));
Sign up to request clarification or add additional context in comments.

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.