Skip to content
Advertisement

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

Advertisement

Answer

since String.prototype.includes actually checks if a string maybe found within another string (the parameter) MDN String.prototype.includes. that means, for undefined args you could default it to empty string. Empty strings will return true if checked with .includes from any string.

you only check for 2 args which are the author & genre. here’s the example:

const books = [
  {author: "A", genres: ["Horror", "romance"]},
  {author: "B", genres: ["romance"]},
  {author: "X", genres: ["science"]},
  {author: "C", genres: ["science", "Horror"]}
];

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

    console.log('filtered Horror = ', allBooks({}, {genre: 'Horror'}));
    console.log('filtered A and Horror = ', allBooks({}, {author: 'A', genre: 'Horror'}));
    console.log('filtered romance = ', allBooks({}, {genre: 'romance'}));
// for all books result
console.log('filtered romance = ', allBooks({}, {}));
 // for an author result
console.log('filtered author(A) = ', allBooks({}, {author:"A"}));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement