Taken from Execute Program
Write a
safeSqrt
function 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:
The
Math.sign()
method returns1
or-1
if the argument is a positive or negative integer, respectively.