/ Gists / Currying fn
On gists

Currying fn

JavaScript

curryfn.js Raw #

// Currying function for calculating the total price
function calculateTotal(price) {
  return function(tax) {
    return function(quantity) {
      return price * quantity * (1 + tax);
    };
  };
}

// Create a curried function for a specific product
const calculateTotalForProduct = calculateTotal(10.99); // Set the base price

// Calculate the total price for a specific product with 8% tax and 3 quantity
const total = calculateTotalForProduct(0.08)(3);
console.log(`Total Price: $${total.toFixed(2)}`);

curry-composition.js Raw #

/*
https://blog.stackademic.com/spice-up-your-javascript-with-currying-894a7c463d03
*/

/* EX: 1 */
// This is a very common compose function, nothing fancy
function compose(...funcs) {
    return funcs.reduce((f, g) => (...args) => f(g(...args)));
}

const double = x => x * 2;
const increment = x => x + 1;

const transform = compose(increment, double);  // Double then increment
console.log(transform(5));  // Outputs: 11 (5 * 2 + 1)


/* EX: 2 */
// Curried functions
const filterByPrice = threshold => products => products.filter(p => p.price >= threshold);
const applyDiscount = percentage => products => products.map(p => ({ ...p, price: p.price * (1 - percentage) }));
const calculateTotal = products => products.reduce((acc, p) => acc + p.price, 0);

// Function composition helper
const compose = (...funcs) => data => funcs.reduce((value, func) => func(value), data);

// Sample products
const products = [
  { id: 1, name: 'Laptop', price: 1000 },
  { id: 2, name: 'Mouse', price: 50 },
  { id: 3, name: 'Keyboard', price: 150 },
  { id: 4, name: 'Monitor', price: 300 },
  { id: 5, name: 'Headphones', price: 80 }
];

// Combined function using currying and composition
const getTotalAfterDiscount = compose(
  filterByPrice(100),         // Filters out products priced below 100
  applyDiscount(0.1),         // Applies a 10% discount
  calculateTotal              // Calculates the total price
);

console.log(getTotalAfterDiscount(products));  // Outputs: 1305 (90% of 1000 + 90% of 300 + 90% of 150)

curry.js Raw #

function sum(a, b, c) {
    return a + b + c;
}

// Curried version of the sum function
function curriedSum(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        };
    };
}

// Using the curried function
console.log(curriedSum(1)(2)(3)); // Outputs: 6


// Another practial example
function log(date) {
    return function(importance) {
        return function(message) {
            console.log(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
        };
    };
}

const logNow = log(new Date());
const logInfoNow = logNow("INFO");
logInfoNow("This is an informational message.");