Skip to content

Instantly share code, notes, and snippets.

@HenriqueLimas
Created April 13, 2017 11:40
Show Gist options
  • Select an option

  • Save HenriqueLimas/1dbb8333e22a0293a07f4f2acbaecd2a to your computer and use it in GitHub Desktop.

Select an option

Save HenriqueLimas/1dbb8333e22a0293a07f4f2acbaecd2a to your computer and use it in GitHub Desktop.
'use strict'
const compose = (...fns) => x => fns.reduce((acc, curr) => curr(acc), x)
const double = x => x * 2
const inc = x => x + 1
const doubleAndInc = compose(double, inc)
const Indentity = value => ({
map: fn => Indentity(fn(value)),
valueOf: () => value,
toString: () => `Indentity(${value})`,
[Symbol.iterator]: () => {
let first = true
return {
next: () => {
if (first) {
first = false
return {
done: false,
value
}
}
return {
done: true
}
}
}
},
constructor: Indentity
})
Object.assign(Indentity, {
toString: () => 'Indentity',
is: x => typeof x.map === 'function'
})
const fRange = (start, end) => Array
.from(
{ length: end - start + 1},
(x, i) => start.constructor(i + start)
)
const trace = x => console.log(x)
const u = Indentity(2)
u.map(trace)
u.map(x => x).map(trace)
const r1 = u.map(x => double(inc(x)))
const r2 = u.map(inc).map(double)
r1.map(trace)
r2.map(trace)
trace('Sum values')
const ints = (Indentity(2) + Indentity(4))
trace(ints)
trace('iterator')
const array = [1,2, ...Indentity(3)]
array.map(trace)
trace('Range of Indentity')
const range = fRange(Indentity(2), 4)
range.map(x => x.map(trace))
trace('Check undefined')
const exists = x => (x.valueOf() !== undefined && x.valueOf() !== null)
const ifExists = x => ({
map: fn => exists(x) ? x.map(fn) : x
})
ifExists(Indentity(undefined)).map(trace)
ifExists(Indentity(null))
.map(inc)
.map(double)
.map(trace)
ifExists(Indentity(20))
.map(inc)
.map(double)
.map(trace)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment