javascript return units, if present when multiplying 2 numbers

Tags: javascript
Question!

2 numbers input to my function values are a, "0.045u" and b, "3"

function mult2nums(a,b) {
    var c = null;
    var unitsFora = null;
    var unitsForb = null;
    var cUnits = null;
    //--> issue - unitsFora = ??; // how to strip off units designator
    //--> issue - unitsForb = ??; // how to strip off units designator
    a = isFloat(a); // also works if int
    b = isFloat(b); //
    c = a*b; 
    // add logic to compare unit designators and convert as needed
    return(c+cUnits); // need to return the units, returns a string type
}


Answers

You can use regex to filter out the units:

function mult2nums(a,b) {
    var c = null;
    var cUnits = null;
    var unitRegex = /[A-Za-z].*/g
    var unitsForA = a.match(unitRegex);
    var unitsForB = b.match(unitRegex);
    a = parseFloat(a.replace(unitsForA, ''));
    b = parseFloat(b.replace(unitsForB, ''));
    c = a*b; 
    // add logic to compare unit designators and convert as needed
    return c + cUnits;
}

Note that the code uses the first encounter of character as the start position of the unit. It can handle upper/lower case differences, and units with number in it (e.g. m/s^2). You can modify the code further to suit your specific needs.

jsFiddle sample: https://jsfiddle.net/ywafx1be/

By : J S


Trying to handle an Error thrown from a thread seems to be a suspicious use case...

From Java Doc : "An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it."

The only time I needed to handle Error is when I use third parties that badly manage their exceptions, that throw Error rather than RuntimeException. In this specific cases, you need to catch the Error (or the Throwable) to avoid unexpected application crash.



A Future is an object that represents the result of running your operation, whether it be ready now or at some point in the future. Generally, one will call the get method on said future in order to get a result, particularly if you are passing a Callable rather than a Runnable into your ExecutorService.

If your Runnable/Callable throws an exception, this will be reflected in the Future object. You will be able to test whether the Runnable ran successfully by calling the get method. If it was a clean run, you will get (in this case) null back. If an exception was thrown, then get will throw an ExecutionException, with that exception marked as its cause.

Think of it like a coat check at a music venue. If they lose your coat, they probably won't tell you until you come with your ticket asking for your coat. The Future serves the purpose of your ticket here.

By : Joe C


This video can help you solving your question :)
By: admin