Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active January 29, 2018 08:00
Show Gist options
  • Save aderaaij/8a0594c3ccf856f87ca8cba26488835f to your computer and use it in GitHub Desktop.
Save aderaaij/8a0594c3ccf856f87ca8cba26488835f to your computer and use it in GitHub Desktop.
/*
* Using the library ramda, what is the result of the following code?
* R.reduce((acc,x) => R.compose(R.flip(R.prepend)(acc), R.sum,R.map(R.add(1)))([x,...acc]), [0])([13, 28]);
* Explain each of the steps the best you can.
*/
const R = require('ramda');
// Reduce function iterating over [13, 28]
// starting point: [0]
const test = R.reduce(
(acc, x) => {
console.log(acc, x);
// Compose - right to left function taking in [...acc, x]
// (read everyting within compose from bottom to top)
return R.compose(
// 4. Prepend sum to accumulator array
R.flip(R.prepend)(acc),
// 3. sum of array
R.sum,
// 2. 1++ for each array item
R.map(R.add(1)),
// 1. Take in array of x and acc values
)([...acc, x]);
},
[0],
)([13, 28]);
console.log(test);
// First iteration: accumulator is [0].
// Compose function takes in [0, 13]
// 1++ for each item in array: [14, 1]
// Sum is 15
// Prepend sum to accumulator array: [15, 0]
// Second iteration: accumulator is [15, 0]
// compose function takes in [0, 15, 28]
// 1++ for each item in array: 1, 16, 29
// Sum of [1, 16, 29] is 46
// Prepend sum to accumulator: [46, 15, 0]
// Does `flip` even flip anything?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment