LearnFrenzy
Sign in Take a free test

Arrow Functions · Arrow Functions Coding Problems · Question 7

Partial application with arrow functions in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Write partial(fn, ...preset) that fixes the first arguments of fn, and use it to create a logger with a fixed level and an email sender with a fixed sender address.

Solution
main.js
const partial = (fn, ...preset) => (...rest) => fn(...preset, ...rest);

const log = (level, module, message) => `[${level}] ${module}: ${message}`;
const sendEmail = (from, to, subject) => `${from} → ${to}: ${subject}`;

const warn = partial(log, "WARN");
const dbWarn = partial(log, "WARN", "db");
const fromSupport = partial(sendEmail, "support@lf.in");

console.log(warn("auth", "token expires soon"));
console.log(dbWarn("slow query"));
console.log(fromSupport("asha@lf.in", "Your certificate is ready"));

Output Verified by running it on Node.js

[WARN] auth: token expires soon
[WARN] db: slow query
support@lf.in → asha@lf.in: Your certificate is ready

partial returns an arrow that combines the preset arguments with the ones supplied later. Unlike currying, any number of arguments can be fixed at once.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links