Skip to content

Instantly share code, notes, and snippets.

@appsparkler
Last active April 15, 2022 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appsparkler/a4f8163824df4fae5c8f3b089de1ee5b to your computer and use it in GitHub Desktop.
Save appsparkler/a4f8163824df4fae5c8f3b089de1ee5b to your computer and use it in GitHub Desktop.
Functional Programming Notes

Functional Programming

1. Declarative v/s Imperative

FP looks at things as "What to do?" rather than "How to do it?"

  // imperative way of doing things
  const findMean = (...numbers) => {
    let x = 0;
    numbers.forEach((number) => {
      x += number;
    });
    const numberOfNumbers = numbers.length;
    return x / numberOfNumbers;
  };
  
  // declarative way of doing things
  const sum = (numbers) => numbers.reduce((acc, n) => n + acc, 0);
  const findMeanFp = (...numbers) => sum(numbers) / numbers.length;

2. Core Concepts

  1. Immutability
  2. Separating functions and data
  3. First-class functions

4. Advanced Functional Concepts

Partial Application or Currying

Currying allows to create custom functions

const add = (x, y, z) => x + y + z;
console.log(add(1,2,3) // 6

// Lets say we want y and z to be fixed
const addCurry1 = x => (y, z) => x + y + z;
console.log(addCurry1(1)(2,3)) // 6
// Now we can create several add(ers) which would need to be called with two more arguments
const add1 = addCurry1(1) // 1 is already curried-in
console.log(add1(2,3)) // 6
const add2 = addCurry(2) //  2 is already curried-in
console.log(add2(1,3)) // 6

// we can also have another variant
const addCurry2 = (x, y) => z => x + y + z
console.log(addCurry2(1, 2)(3))//6
// Now we can create adders which would require to be called with one more argument
const add1and2 = addCurry2(1, 2)
console.log(add1and2(3)) // 6
const add2and3 = addCurry2(2, 3);
console.log(add2and3(1)) // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment