Skip to content

Instantly share code, notes, and snippets.

@K3ndev
Last active March 26, 2023 16:44
Show Gist options
  • Save K3ndev/88556591b64c96241f22d3abbad5f10f to your computer and use it in GitHub Desktop.
Save K3ndev/88556591b64c96241f22d3abbad5f10f to your computer and use it in GitHub Desktop.

Functional programming

What is functional programming?

  • its a programming paradigm
  • safer/ easy to maintain

Rules

  • Do everything with funcions
  • A function should have one responsibility
  • A function probably needs a guard clause
    • A conditional statement that is used at the beginning of a function to check for invalid input or unexpected conditions.
    • If true, the function immediately stops and returns a value or throws an error, preventing the rest of the code from executing.
  • Avoid side effects [aka it should be pure function]
// not pure function
const name = 'fooName'
function giveName(){
  console.log('name')
}

// pure function
function giveName(name){
  return `this is my name: ${name}`
}

// use arguments, and return something
  • Use Higher order function
    • functions can be inputs/outputs
    • callback function
      • is merely a function that is invoked or carried out inside another function and is passed to it as a parameter.
function makeAdjectifier(adj){
  return function (str) {
    return `${adj} ${str}` 
  }
}

const coolifier = makeAdjectifier('cool')
coolifier('conference') // "cool conference"
const mult = (a,b) => {
    return a*b;
}
const calculator = (num1,num2, operator) => {
  return operator(num1,num2);
}
// mult is also called callback function
console.log(calculator(5,6,mult));
  • Don't iterate
    • use map, filter, reduce
      • map method use HOF
    • iterate like for, while, for in, for of
  • Avoid mutability
    • use immutable data
      • immutable means the data doesnt change
// mutation (bad code!)
let data = ['a', 'b', 'c']
data[1] = 'changed'
  • We should think that all data is immutable
    • you can also use Object.freeze()
// no mutation (good code!)
const data = ['a', 'b', 'c']
function getNewData (data, newItem){
  return data.map((item) => {
    if(item === 'b'){
      return newItem
    }
    return item
  })
}

const newData = getNewData(data, 'changed')
  • Persitent & immutable data structures for efficient immutability
    • immutable data structure
      • never changes
    • Persitent data structure
      • have acces to prev version
    • Path copying
      • use persitent and immutable data structure
      • more performant
      • creating another node, for new data without changing the original data or replacing
      • lib: immutable.js, mori
  • Use recursion to handle repitition
    • doing recursion has limitation because of call stacks
    • some js engines have tail call optimization to solve the issue
// non tail-recursive
const recursiveInception = (n) => {
  if(n === 0) return "a dream"
  
  
  let dreams = recursiveInception(n-1)
  return dreams + " within a dream"
}

console.log(recursiveInception(5))
// tail-recursive (dreams+)
// it use accumulator to keep track of the sequence without using additional memory for a call stack
const tailRecursiveInception = (n) => {
	const incept = (n, dreams) => {
  	if(n === 0) return dreams;
    return incept(n-1, dreams+" within a dream")
  
  }
 
 return incept(n, "a dream")
}

console.log(tailRecursiveInception(5))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment