Skip to content

Instantly share code, notes, and snippets.

@chety
Created September 21, 2022 11:39
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 chety/fceaf163701ddabc942a887a3d0c21d9 to your computer and use it in GitHub Desktop.
Save chety/fceaf163701ddabc942a887a3d0c21d9 to your computer and use it in GitHub Desktop.
Higher order functions re-implementation in Javascript
function filter(predicateFn,arr) {
    if(length(arr) === 0) {
        return []
    }
    const firstElement = head(arr)
    const firstElementFilter = predicateFn(firstElement) ? [firstElement] : []
    return concat(firstElementFilter, filter(predicateFn,tail(arr)))
    
}

function map(fn, array) {
  if(length(array) === 0) {
      return []
  }
  const firstElement  = head(array)
  const firstElementMap = [fn(firstElement)]
  return concat(firstElementMap,map(fn,tail(array)))  
}

function reduce(fn,arr,initialValue) {
    if(length(arr) === 0){
        return initialValue;
    }
    const initial = initialValue ?? head(arr);
    const newArr = isPresent(initialValue) ? arr : tail(arr)
    const newInitialValue = fn(initial,head(newArr))
    return reduce(fn,tail(newArr),newInitialValue)
}

function some(predicateFn, arr) {
    for (let value of arr) {
        if(predicateFn(value)){
            return true
        }
    }
    return false
}


function isPresent(val) {
    return val !== undefined && val !== null
}

function length(arr) {
    return arr.length
}
function head(arr) {
    if(length(arr) === 0){
        return
    }
    return arr[0]
}

function tail(arr) {
    if(length(arr) === 0){
        return
    }
    return arr.slice(1)
}

function concat(arr1,arr2) {
    return arr1.concat(arr2)
}

const double = n => n * 2;
const isEven = n => n % 2  === 0;
const isPrime = n => {
    if(n <  2){
        return false
    }
    for (let i = 2; i <= n / 2; i++) {
        if (n % i === 0){
            return false
        }
    }
    return true
}

const isPrimeFunctional = n => {
    if(n < 2){
        return false
    }
    const wholes = [2,3,5,7];
    const possibleFactors = filter(num => num <= Math.sqrt(n), wholes )
    return !some(num => n % num === 0, possibleFactors)
}


const fizzBuzz = n => {
      let result = ''
      result += 'fizz'.repeat(n % 3 === 0)
      result += 'buzz'.repeat(n % 5 === 0)
      return result || n;
}

const fizzBuzz2 = n => {
      const fizzed = n % 3 === 0 ? 'fizz' : '';
      const buzzed = n % 5 === 0 ? 'buzz' : '';
      return fizzed || buzzed ? fizzed + buzzed : n ;
}

const product = (num1,num2) => num1 * num2;
const sumOfTwo = (num1,num2) => num1 + num2;

const arr = Array(100).fill(0).map((_,i) => i + 1)
console.log('Primes:',filter(isPrimeFunctional,arr))
console.log('FizzBuzz:',map(fizzBuzz2,arr))
console.log(reduce(sumOfTwo,arr,0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment