How do I eliminate all these if-else

I have written this code to filter a "books" array, depending on the author or genre have been given as a parameter:-

//This code works perfectly fine as is
allBooks: (root, args) => {
      if (args.author === undefined && args.genre === undefined) {
        return books
      } else if (args.author === undefined) {
        return books.filter((book) => book.genres.includes(args.genre))
      } else if (args.genre === undefined) {
        return books.filter((book) => book.author === args.author)
      } else {
        const booksFilter = books.filter((book) => book.author === args.author)
        return booksFilter.filter((book) => book.genres.includes(args.genre))
      }
    }

I believe there must be some way to write this more "professionally" without using all these if-else. So if anyone knows a better way, I'll appreciate it.

[Edited] Thanks to all, I decided to go with ghostkraviz solution, code looks like this now:

allBooks: (root, args) => {
      return books.filter((book) => {
        const filteredGenres = book.genres.filter((genre) =>
          genre.includes(args.genre || "")
       );
       return book.author.includes(args.author || "") && filteredGenres.length > 0;
      })
    }


Read more here: https://stackoverflow.com/questions/64942104/how-do-i-eliminate-all-these-if-else

Content Attribution

This content was originally published by luthai at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: