Search code examples
javascriptecmascript-6higher-order-functions

I can't understand how the logic flow of this ES6 higher-order function


how the logic flows at: (books) => (shelf) => ...

const shelf1 = [
  { name: "name1", shelf: "a" },
  { name: "name2", shelf: "a" },
];
const shelf2 = [
  { name: "name3", shelf: "b" },
  { name: "name4", shelf: "b" },
];
const allBooks = [...shelf1, ...shelf2];

const filter = (books) => (shelf) => books.filter((b) => b.shelf === shelf);

const filterBy = filter(allBooks);
const booksOnShelf = filterBy("b");

i need a more verbose equivalent to this shortened expression, to help me to digest that magic


Solution

  • It's a function that accepts a books argument and returns a new function that accepts a shelf argument. That function is assigned to filterBy, and the result of calling that function (an array) is assigned to booksOnShelf.

    The inner function maintains a reference to books when it's returned, and is generally called a closure.

    const shelf1=[{name:"name1",shelf:"a"},{name:"name2",shelf:"a"}],shelf2=[{name:"name3",shelf:"b"},{name:"name4",shelf:"b"}];
    
    const allBooks = [...shelf1, ...shelf2];
    
    function filter(books) {
      return function (shelf) {
        return books.filter(function (b) {
          return b.shelf === shelf;
        });
      };
    }
    
    // `filter` returns a new function which
    // is assigned to `filterBy`. That function accepts
    // a `shelf` argument
    const filterBy = filter(allBooks);
    
    // The result of calling that new function with
    // argument 'b' is assigned to `booksOnShelf`
    const booksOnShelf = filterBy('b');
    
    console.log(booksOnShelf);