Elm Result in JS

by de Montalembert Jonathan

JavaScript

var Result = {
  Ok: (a) => ({
    ap: b => b.map(a),
    map: f => Result.Ok(f(a)),
    mapError: (_) => Result.Ok(a),
    andThen: f => f(a),
    fold: (f, g) => g(a),
    withDefault: (_) => Result.Ok(a)
  }),
  Err: (a) => ({
    ap: b => Result.Err(a),
    map: (_) => Result.Err(a), // we dont want to execute map when our function has failed to return a valid value
    mapError: f => Result.Err(f(a)),
    andThen: f => f(a),
    fold: (f, g) => f(a),
    withDefault: (v) => Result.Ok(v)
  }),
  exec: (f) => f(Result.Err, Result.Ok),
  of: a => Result.Ok(a)
}

var execDemo = () => {
  return Result.exec((rej, res) =>
    res(1))
}

execDemo().map(x => x * x + x).fold((x) => console.log('failed', x), (x) => console.log('congrats', x))

Result.of(1).map(x => x + x).fold(x => console.log('err with of', x), succ => console.log('success with of', succ))

function predemo(shape) {
  var found = {
    triangle: 3,
    square: 4
  }[shape]
  return found ? found : false;
}

function demo(shape) {
  var found = {
    triangle: 3,
    square: 4
  }[shape]
  return found ? Result.Ok(found) : Result.Err(shape + ' not found')
}

function powIfOdd(v) {
  return v % 2 == 0 ? Result.Ok(v * v) : Result.Err('not odd')
}

var someOperation = x => v => x + v + 5;

	Result.of(someOperation) // demo('triangle')
  .ap(demo('triangles')) // map(someOperation)
  .ap(powIfOdd(4))
  .fold((msg) => console.log('Error: ' + msg), res => console.log('Success: ' + res))