DEV Community

Discussion on: JavaScript: Write cleaner code with Functional Programming

Collapse
 
vonheikemen profile image
Heiker

May I suggest also creating more "generic" helper functions. Not sure how readable this is but I'd like to show how far you can get using general purpose functions.

Forgive my use of var, I was testing this in the console.

var devArticlesApiURL = 'https://dev.to/api/articles';

var bindMethod = (method) => (obj) => obj[method].bind(obj);
var compose = (...fns) => initial => 
  fns.reduceRight((state, fn) => fn(state), initial);

var filter = (fn) => (arr) => arr.filter(fn);
var getProp = (key) => (obj) => obj[key];

var hasTags = tags => compose(
  bindMethod('every')(tags),
  bindMethod('includes'),
  getProp('tag_list')
);

var filterJSTags = filter(hasTags(['javascript', 'node']));

var fetchJSDevArticles = () =>
  fetch(devArticlesApiURL)
    .then(response => response.json())
    .then(filterJSTags);

fetchJSDevArticles().then(console.log);
Collapse
 
r0r71z profile image
Raddelyn Ortiz

Hey, what you've done here is really cool. I definitely think this pattern is valuable, especially when your intention is to have "similar" functions in your projects. Thanks!

BTW: Most modern browsers support the newest JavaScript versions, so you should be able to run ES6+ syntaxes on the console.

Collapse
 
vonheikemen profile image
Heiker

The problem is not the browser, is me. I made a lot of mistakes while making that snippet, so I had to run it multiple times. If I use const I would have to keep changing the variable names after each attempt, 'cause const doesn't let me redeclare variables.