DEV Community

Discussion on: JavaScript error handling pattern tip

Collapse
 
vonheikemen profile image
Heiker

If you're going to use tags and helper functions, why not go for a little pattern matching too?

function match(value, patterns) {
  const { type = null } = value || {};
  const _match = patterns[type];

  if(typeof _match == 'function') {
    return _match(value.data);
  } else if (typeof patterns._ == 'function') {
    return patterns._();
  }
  else {
    return;
  }
}

function Union(types) {
  return types.reduce((target, type) => {
    target[type] = (data) => ({
      type,
      data,
      match: patterns => match({type, data}, patterns)
    });
    return target;
  }, {});
}

Then you can have this.

const Result = Union(['Ok', 'Err']);
const something = Result.Ok({ stuff: 'good stuff' });
const maybe = Result.Err('this is still data');

something.match({
  Ok: ({stuff}) => `the ${stuff}`,
  Err: (msg) => msg,
  _: () => 'What?'
});

// the good stuff

For a better version of that checkout this library.

Collapse
 
max_frolov_ profile image
Max Frolov

Thanks for the suggestion, nice lib :) I use FP-TS and the pattern above is an abstract demonstration of the way of thinking