2023-04-27

 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 }.

Solution

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.

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAZwIbAKYGUCOAnKACjAC5EwQBbAIwzwEpEBvAWAChFEZhFDEA5KrTwA6GMn6p+xRgB9ZiALKooACxHIYAczAzEAXkOIAtAEZEjVh06I8GKCDxImiANYwwAEzIByYKhgAG0cMH0QAX3ZOSOs7BydmNw9vRB9kEAgIDGRkHwAaRAA3VGCMMmU1DXwiMEYYmPY0TFwCQgAGRgB6TsT3L190zOzcguLSsjaI9kb0bGrCUy6elz6UtIysnPyikpAyxHMGtia51tM2i47Ebt7kgY3h7bG9snPJo5OWojMl2-7U-xBEJhD6zL6EMwXX4rO4AgLBOwg6bHMHzST8aFJf5+eHAqZsIA

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