1

I am once again doing some Selenium automation in JavaScript and I have some methods that return boolean values about the webpage. For instance, I have a method isB2B() which returns whether the order form I'm automating is for a B2B order. It relies on the private #getMarketType() method, which returns either the Market Type as a string or false, depending on whether it was able to retrieve the market type from the page using Selenium. I would like the return value for the isB2B() method to indicate both the success value of the retrieval and whether the market type was B2B. In Rust, I would use the enum

Result<bool, ()>

which could have either variant of

Ok(bool)

or

Err(())

How can I achieve similar functionality in JavaScript?

  • I don't think you can really do anything equivalent in any dynamically-typed language like JS. The idiomatic JS way to handle this specific situations would probably be to throw an exception in the error case, and then attempt to handle that in any functions that call this one. – Robin Zigmond Aug 24 '21 at 22:06
  • 1
    You can always define your own `Result` object in JS with functions to manipulate it like Rust has. Is that something you've explored? – loganfsmyth Aug 24 '21 at 22:10
  • 1
    You could return an object, for example `{success: true}` on success or `{error: {}}` on fail and check if `typeof result.error != "undefined"` to see if there was an error. Another way would just be to return a boolean or an error object depending on whether it was successful and check if `typeof result == "object"` to see if it was an error. Another way would be to pass along two callback parameters (one for success, and one for failure), and call the respective callback depending on whether the function was successful. – Liftoff Aug 24 '21 at 22:13
  • All of these comments were helpful, thank you! @loganfsmyth I thought about this, but I wanted to do something that wouldn't totally confuse a JavaScript developer when they saw it. I have been using es6 classes with static members to work like enums, and I bet with some finagling I could make a Result. – Benjamin Peinhardt Aug 24 '21 at 22:46
  • @David Those shapes are better than what I came up with, as I was going to pass back something like a tuple. – Benjamin Peinhardt Aug 24 '21 at 22:48
  • 1
    @BenjaminPeinhardt It wouldn't be totally confusing, just a bit non-mainstream. There are lots of functional-programming libraries that ship `Result` or `Either` data structures. – Bergi Aug 24 '21 at 23:23
  • Take a look at [@polkadot/types](https://github.com/polkadot-js/api/tree/a1f07e32743eed1c27bf06ca6fb9118afdbfa839/packages/types). They have completely ported the Rust type system to JS. [Here](https://github.com/polkadot-js/api/blob/a1f07e32743eed1c27bf06ca6fb9118afdbfa839/packages/types/src/codec/Option.ts) is the spec for Option. – forgetso Aug 25 '21 at 14:50

0 Answers0