Skip to content

Instantly share code, notes, and snippets.

@kylejeske
Last active January 8, 2021 15:52
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 kylejeske/7ab6d8185ece58db23173e795fe3c797 to your computer and use it in GitHub Desktop.
Save kylejeske/7ab6d8185ece58db23173e795fe3c797 to your computer and use it in GitHub Desktop.
High Order Functions: Break down of Fold (Reduce) in JavaScript

Fold

About a high-order functions:

High-Order Function, as a structural transformation, the fold is a polymorphic function.

(The breakdown)

This just means, it takes on different forms (poly = multiple), and can take data from one element and transform it into another.

Specifically, this is speaking to the 'left fold'.

Key points:

  • explained in category theory
  • catamorphism, uses 'typed calculis' (Lambda) to explain the fold of a list.
  • typically a linear function applied to a finite set.

We call this in JavaScript: Reduce

(() => {
/**
* For Reference, I peronsally find it important to
* understand the background in the tools I use.
*
* In this particular case, it's part of discrete math.
* And the concept is:
* apply a function, against a sequence of elements
* and yield (return) a product of that function.
*
* Reduce :
* ( f x e -> f ) x Seq<e> x f -> f
*/
const produceSumOfSequenceElements = (sequence, element) => {
return sequence + element;
}
const getTotalSum = (elements = [], operatorFunction) => {
return elements.reduce(
operatorFunction,
0
)
};
// Testing Assumptions
const testTaskSumOfSequence = (verbose = true) => {
const elements = [5, 2, 6, 9, 10];
const expectedSum = 32;
const sumOfSequence = getTotalSum(elements, produceSumOfSequenceElements);
if (verbose) {
console.log(`Task:`);
console.log(`Get the sum of elements in sequence:\n${elements}.\n\n`);
console.log(`Expected result:\n${expectedSum}.\n\nActual result:\n${sumOfSequence}.`);
}
if (expectedSum === sumOfSequence) {
console.log(`> Task Status: Passed.`);
} else {
console.log(`> Task Status: Failed.`);
}
};
testTaskSumOfSequence(false);
/**
Result:
Task:
Get the sum of elements in sequence:
5,2,6,9,10.
Expected result:
32.
Actual result:
32.
> Task Status: Passed.
*/
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment