Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading