Skip to content
Carlos De Dios edited this page Oct 20, 2015 · 1 revision

Description

Chainer of conditions and actions for a value.

For value a, when condition ca is fulfilled do op1 otherwise do op2

Could work as replacement for switch/case and if/else if/else.

Example

/* Regular Approach */

let value = getRandomValue();
let res = 0;

switch(value) {
  case  5:
    res = value * 20;
    break;
  case 10:
    res = value * 10;
    break;
  case 20:
    res = value *  5;
    break;
  default:
    res = value;
    break;
}

let response = res;

if (response % 20 === 0) {
  response -= 20;
} 
if (response % 10 === 0) {
  response -= 10;
} else {
  response -= 5;
}

response -= 25;

return response;

/* Given Approach */

import { given } from "functional-programming-utilities";

let value = getRandomValue();

let makeHigherOrder = (f) => (b) => (a) => f(a, b);
let equalTo = makeHigherOrder((a, b) => a === b);
let subtract = makeHigherOrder((a, b) => a - b);

let multiplyBy = makeHigherOrder((a, b) => a * b);
let divisibleBy = makeHigherOrder((a, b) => a % b === 0);

return (
  given(value)
    .when(equalTo(5))
      .then(multiplyBy(20))
    .when(equalTo(10))
      .then(multiplyBy(10))
    .when(equalTo(20))
      .then(multiplyBy(5))
    .when(divisibleBy(20))
      .then(subtract(20))
    .when(divisibleBy(10))
      .then(subtract(10))
      .otherwise(subtract(5))
    .apply(subtract(25))
    .out());

As you can see this approach allows for a far more clear and sentence like composition.

Clone this wiki locally