Skip to content

Instantly share code, notes, and snippets.

@petyappetrov
Last active March 16, 2017 22:07
Show Gist options
  • Save petyappetrov/f64dd8fafa664e5af7d8cc449e99bfd9 to your computer and use it in GitHub Desktop.
Save petyappetrov/f64dd8fafa664e5af7d8cc449e99bfd9 to your computer and use it in GitHub Desktop.
/////////////////////////////////////////////////////////////////////////////////////////
function sequence (start, step) {
return function () {
return start += step
}
}
/////////////////////////////////////////////////////////////////////////////////////////
function square (a) {
return a * a
}
/////////////////////////////////////////////////////////////////////////////////////////
function add (a, b) {
return a + b
}
/////////////////////////////////////////////////////////////////////////////////////////
function take (fn, count) {
if (typeof fn !== 'function') {
throw 'Error: Function is not valid'
}
if (!count) {
throw 'Error: Please set up count calling of function'
}
const array = []
for (var i = 0; i < count; i++) {
array.push(fn())
}
return array
}
/////////////////////////////////////////////////////////////////////////////////////////
function map (fn, array) {
if (typeof fn !== 'function') {
throw 'Error: Function is not valid'
}
if (!Array.isArray(array)) {
throw 'Error: Second argument is not array'
}
return array.map(fn)
}
/////////////////////////////////////////////////////////////////////////////////////////
function fmap (outerFn, innerFn) {
if (typeof outerFn !== 'function') {
throw 'Error: outerFn is not valid function'
}
if (typeof innerFn !== 'function') {
throw 'Error: innerFn is not valid function'
}
return function () {
/**
* I hope you remember about – bind, call, apply :)
*/
return outerFn(innerFn.apply(this, arguments))
}
}
/////////////////////////////////////////////////////////////////////////////////////////
function initialize () {
// const gen = sequence(1, 1)
// const test = take(gen, 5)
// console.log('Test take:', test)
// const squareArray = map(square, [2, 4, 6])
// console.log('Square array:', squareArray)
const generator = sequence(1, 1)
const squareGen = fmap(square, generator)
console.log('Square gen:', squareGen())
console.log('Square gen:', squareGen())
const squareAdd = fmap(square, add)
console.log('Square add:', squareAdd(2, 3))
console.log('Square add:', squareAdd(5, 7))
}
/////////////////////////////////////////////////////////////////////////////////////////
try {
initialize()
} catch (err) {
console.error(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment