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:

// typescript

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:


Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

[ this node is permanently morphing last updated on 28 May 2023 ]

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