Taken from Execute Program
Write a
safeSqrtfunction that wrapsMath.sqrt, but returns a union type to indicate errors. It should only work for positive numbers and zero. That will force callers to handle the error when the argument is a negative number.If the input is negative, your function should return an object with
{kind: 'failure'}. If the input is positive or zero, it should return an object with{kind: 'success', value: VALUE }.
Solution
This is the answer I came up with:
function safeSqrt(n: number) {
  if ( Number.isNaN(n) || Math.sign(n) === -1 ) {
    return { kind: 'failure' }
  }
  return { kind: 'success', value: Math.sqrt(n) }
}The
Math.sign()method returns1or-1if the argument is a positive or negative integer, respectively.