Reducing complexity

See http://mdworld.nl/blog/webdevelopment/2017/10/02/reducing-complexity/

by mdvanes

HTML

Check out the JavaScript console for the result.

JavaScript

// Second part
function example(error, stdout, stderr, mapping) {
  const actions = [{
    condition: _ => !stdout || stdout.length <= 0,
    action: _ => console.log('No result')
  }, {
    condition: _ => !Array.isArray(mapping),
    action: _ => console.log('Config invalid')
  }, {
    condition: _ => error || (stderr && stderr.length > 0),
    action: _ => console.log('Error executing')
  }, {
    condition: _ => stderr && stderr.length > 0 && stderr.indexOf('A problem occurred') > -1,
    action: _ => console.log('Not found')
  }];

  const selectedAction = actions
    .filter(action => action.condition())
    .reduce((accumulated, currentAction) => {
      // By design, reduce will only keep the last match when the accumulator 
      // is ignored, so the order inside the actions array has significance.
      return currentAction.action;
    }, function() {
      // Else clause
      console.log('Result from some process with mapping and stdout');
    });
  selectedAction();
}

example(null, null, 'A problem occurred'); // Logs "Not found"
example(new Error()); // Logs "Error executing"
example(null, null, null, null); // Logs "Config invalid"
example(null, '', null, []); // Logs "No result"
example(null, 'Foo', null, []); // Logs "Result from some process with mapping and stdout"