DEV Community

Discussion on: JavaScript Bites: Closure

Collapse
 
bamartindev profile image
Brett Martin

Hi zaferberkun - thanks for the comment!

I can see what you are saying - I think I need to come up with a better example in this case to show the partial application, as the underlying console.log only takes the one argument.

How about a simple add example in its place, where the example of the closure is in the partial function definition:

const partial = (fn, arg) => {
  return (...args) => {
    return fn(arg, ...args);
  };
};

const add = (x, y) => x + y;

const add10 = partial(add, 10);

console.log(add10(5));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zaferberkun profile image
zaferberkun

Hi Brett,

I like that! Also, after some consideration, I think I was actually wrong and your original example (and the one by peerreynders below) is a perfectly valid example of partial application.

What threw me was the use of an "intermediary" make function to create the partial. What I was expecting was that the function itself, logger in this case, could be applied partially "in place". You would have to add "undefined" arg checks, but that way you could do full or partial application without "intermediary" maker functions for each arg permutation. Of course, if you're planning using composition, you'll need to generate a partial that only takes one arg (which your logger make example is doing). Anyway, sorry about that, you can disregard my original post if you want.

Btw, great writing, hope you'll tackle some more functional programming concepts! I'm going to have to backtrack and read the ones you've already written.

Collapse
 
peerreynders profile image
peerreynders • Edited

I think I need to come up with a better example in this case to show the partial application, as the underlying console.log only takes the one argument.

const docLogger = mkLogger('DOCS', true);

logger('LIBS', 'Direct log message', false);
docLogger('This is my log message');
docLogger('Another log message');

function logger(route, message, showDate) {
  const header = showDate ? `${new Date().toISOString()} | ${route}` : route;
  console.log(`${header} | ${message}`);
}

function mkLogger(route, showDate = false) {
  // Implement "partial application" with the values
  // in the closure
  return (message) => logger(route, message, showDate);
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
bamartindev profile image
Brett Martin

Thanks for writing this up - ill add it to the main article and shout you out!