Skip to content

Commit

Permalink
feat: Update "when" to return thenFn or elseFn if not functions
Browse files Browse the repository at this point in the history
  • Loading branch information
andreidmt committed Aug 26, 2020
1 parent ae5b55b commit dcaedb4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/when/when.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { type } from "../type/type"
import { is } from "../is/is"

/**
* Functional if-then-else
*
* @param {Function} ifFn Condition function
* @param {Function} ifFn Condition
* @param {Function} thenFn Then function
* @param {Function} elseFn Else function, if not specified will return
* source
Expand All @@ -16,14 +16,18 @@ import { type } from "../type/type"
* @example
* when(isEven, increment, decrement)(5)
* // => 6
*
* when(isOdd, increment)(6)
* // => 6
*/
const when = (ifFn, thenFn, elseFn) => source =>
ifFn(source)
? thenFn(source)
: type(elseFn) === "Function"
? elseFn(source)
: source
export const when = (ifFn, thenFn, elseFn) => source => {
if (ifFn(source)) {
return typeof thenFn === "function" ? thenFn(source) : thenFn
}

if (typeof elseFn === "function") {
return elseFn(source)
}

export { when }
return is(elseFn) ? elseFn : source
}
12 changes: 12 additions & 0 deletions src/when/when.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ import { inc, dec, when } from ".."
const isEven = source => source % 2 !== 0

test("when", t => {
t.equals(
when(isEven, "even", "odd")(5),
"even",
"Primitive instead of then function"
)

t.equals(
when(isEven, "even", "odd")(6),
"odd",
"Primitive instead of else function"
)

t.equals(
when(isEven, inc, dec)(5),
6,
Expand Down

0 comments on commit dcaedb4

Please sign in to comment.