27 Apr 2023

Write a Safe Square Root function that returns a Union Type to indicate Errors

Taken from Execute Program

Write a safeSqrt function that wraps Math.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 }.


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 returns 1 or -1 if the argument is a positive or negative integer, respectively.


Solution tested in REPL:


Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems