Last active
February 4, 2016 15:04
-
-
Save jacob-faber/93362aa933e9cf4d1d22 to your computer and use it in GitHub Desktop.
Base Functions in functional programming (without error checking for brevity)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const expect = require('chai').expect; | |
const array1 = [1, 2, 3]; | |
const array2 = [1]; | |
const array3 = []; | |
// Let's define fundamental building block | |
function each(arr, fn) { | |
for (let i = 0, l = arr.length; i < l; ++i) { | |
fn(arr[i], i) | |
} | |
} | |
each(array1, (elem) => console.log(elem)); | |
each(array2, (elem) => console.log(elem)); | |
each(array3, (elem) => console.log(elem)); | |
function reduce(arr, fn, initial) { | |
let acc = initial; | |
each(arr, (elem) => { | |
acc = fn(acc, elem) | |
}); | |
return acc; | |
} | |
expect(reduce(array1, (acc, elem) => acc + elem, 0)).equal(6); | |
expect(reduce(array2, (acc, elem) => acc + elem, 0)).equal(1); | |
expect(reduce(array3, (acc, elem) => acc + elem, 0)).equal(0); | |
// Transform | |
function map(arr, fn) { | |
return reduce(arr, (acc, elem) => { | |
return acc.concat(fn(elem)); | |
}, []) | |
} | |
expect(map(array1, (elem) => elem * 2)).eql([2, 4, 6]); | |
expect(map(array2, (elem) => elem * 2)).eql([2]); | |
expect(map(array3, (elem) => elem * 2)).eql([]); | |
// Filter by predicate p from fn() | |
function filter(arr, fn) { | |
return reduce(arr, (acc, elem) => { | |
if (fn(elem) === true) | |
return acc.concat(elem); | |
else | |
return acc; | |
}, []) | |
} | |
expect(filter(array1, (elem) => elem >= 2)).eql([2, 3]); | |
expect(filter(array2, (elem) => elem < 1)).eql([]); | |
expect(filter(array3, (elem) => elem < 2)).eql([]); | |
// Zip or in CS(Convolution) | |
function zip(...arrays) { | |
const len = arrays[0].length; | |
let result = []; | |
for (let x = 0; x < len; ++x) | |
result[x] = [] | |
for (let i = 0, l = arrays.length; i < l; ++i) { | |
for (let j = 0, l2 = len; j < l2; ++j) { | |
result[j % len][i] = arrays[i][j]; | |
} | |
} | |
if (result.length === 1) | |
return result[0]; | |
else | |
return result; | |
} | |
expect(zip(['fred', 'barney'], [30, 40], [true, false])).eql([['fred', 30, true], ['barney', 40, false]]); | |
expect(zip([1, 2, 3], [1, 2, 3])).eql([[1, 1], [2, 2], [3, 3]]); | |
expect(zip([2], [3], [4])).eql([2, 3, 4]); | |
expect(zip([], [])).eql([]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment