Skip to content

Instantly share code, notes, and snippets.

@miladvafaeifard
Last active January 3, 2019 14:47
Show Gist options
  • Save miladvafaeifard/5f80b945d9ac9d8a29ee19b609fef6cd to your computer and use it in GitHub Desktop.
Save miladvafaeifard/5f80b945d9ac9d8a29ee19b609fef6cd to your computer and use it in GitHub Desktop.
functional compositions
//*********************** as libraries ***********************
const pipe = (...functions) => v => functions.reduce((y, f) => f(y), v)
const mapFn = f => arr => arr.map(f)
const trace = key => value => console.log(`${key} : ${value}`)
// TODO: need improvements
const expect = actual => ({
toBe: expected => {
if (Array.isArray(expected)) {
if (expected.length > 0 && expected.length === actual.length) {
return expected.every((e, i) => e === actual[i])
}
return false
} else if (typeof expected === 'number') {
return actual === expected
}
throw "is not able to maintain."
}
});
//*********************** [TEST] multiply by 2 ***********************
const multiply2 = pipe(
mapFn(x => x * 2)
)
console.log(
expect(multiply2([1, 2, 3])).toBe([2, 4, 6]),
)
//*********************** [TEST] add with 5 ***********************
const add5 = pipe(
mapFn(x => x +5)
)
console.log(
expect(add5([1,2,3])).toBe([6, 7, 8]),
)
//*********************** [TEST] convert first letter of string to upper case ***********************
const firstLetterUpper = pipe(
mapFn(s => s[0].toUpperCase() + s.substring(1)),
)
console.log(
expect(firstLetterUpper(['milad', 'hello'])).toBe(['Milad', 'Hello']),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment