I created the following Typescript extension to convert a string to Number:
declare global {
interface String {
toNumber(): number | null;
}
}
String.prototype.toNumber = function(this: string) {
return parseFloat(this);
}
When it is not possible to parse the string to number either because it is invalid, null, undefined, etc I would always like to return null.
How can I do this?
I am assuming you already understand the differences between parseFloat / Number as conversion mechanisms.
Effectively all you need to do is check if the output is NaN. You can do this by:
String.prototype.toNumber = function(this: string) {
const num = parseFloat(this);
return Number.isNaN(num) ? null : num;
}
If you want to return either a non-zero valid number (well, note that NaN is a number, but I think I know what you mean), then check for what you don't want before returning:
Object.defineProperty(String.prototype, "toNumber", {
value: function(str) {
let num = Number(str);
return num === 0 || isNaN(num) ? null : num;
}
});
(Defining properties directly on the prototype is a bad habit and can lead to weird behavior; using .defineProperty gives you a property that is not enumerable.)
Oh, and that's JavaScript, obviously, not Typescript.
A simple answer would be to use return Number(this) || null;
The Number function will convert to a number or NaN, NaN || null will return null (because NaN is falsey).
Updated added testing for zero condition, which with the above code would have also returned null. If that is not what you want, this code will allow zero to return. (Note that this can be done many different ways!):
const parsedValue = Number(this);
return parsedValue === 0 ? parsedValue : parsedValue || null;
Updated to use the parseFloat function, example of early exit for string of '0'. Very similar to the previous updated example.
if (this === '0') {
return 0;
}
return parseFloat(this) || null;
I have a jquery function which receives a parameter from it callers. Calling split() on the parameter throws error. Here is the function
function formatNairaCurrency(value) {
var formatedWithoutNaira;
var formattedAmount
//check if value is in kobo format
var splittedValue = value.split(".");//Throws error
if (splittedValue.length === 2) {
formatedWithoutNaira = isNaN(splittedValue[0]) ? "" : splittedValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + splittedValue[1];
} else {
formatedWithoutNaira = isNaN(value) ? "" : value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + ".00";
}
return formattedAmount;}
The call var splittedValue = value.split("."); throws the error value.split is not a function
What am I missing?
I am calling this in a .cshtml file. This works in another function even on the same .js file. The difference is that the value was not a parameter but a value from a text box.
Your help is greatly appreciated.
If i understand your intention correctly you are trying to use split for string. Your error could be caused by the fact that value is not string. You need to debug or throw to console 'value'.
Edit: For example if
value is null, or value is undefinded this would most definitely cause your error. Testing for those conditions:
(value === null)
(typeof value === 'undefined')
If your value is number - that would cause error too. You need to cast number to string first. You can do it by
var valueAsString = value.toString();
valueAsString.split('.');
I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.
The following works for all cases except when the string is "0" in which case it returns null.
parseInt(columnSortSettings[0]) || null;
How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!
Since 0 is act as false , so you can use isNaN() in this case
var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
It's because you are basically testing 0 which is also false.
You can do
var n = columnSortSettings[0];
if(parseInt(n, 10) || n === '0'){
//...
}
You can also test instead if it's a number
if(typeof(parseInt(n, 10)) === 'number'){
//...
}
But beware cause
typeof Infinity === 'number';
typeof NaN === 'number';
You can use the isNumeric operator from rxjs library (importing rxjs/util/isNumeric
model.qty = (parseInt($('#amendOrderQty').val()) == NaN) ?
0 :
parseInt($('#amendOrderQty').val());
// model.qty === NaN when #amendOrderQty is left blank
I am trying to set a value of 0 when the field is left blank. Why does this not work?
You cannot use the comparison operator with NaN, it will always return false.
Use isNaN() instead
var qty = parseInt($('#amendOrderQty').val());
model.qty = isNaN(qty) ? 0 : qty;
Use "isFinite" instead.
var x = parseInt($('#amendOrderQty').val();
model.qty = isFinite(x) ? x : 0;
You cannot directly compare something to NaN because
NaN === NaN
always returns false.
In light of this, you should replace
parseInt($('#amendOrderQty').val()) == NaN
with
isNan(parseInt($('#amendOrderQty').val()))
Your code, refactored and fixed, should look something like this:
var orderQtyVal = parseInt($('#amendOrderQty').val());
model.qty = isNaN(orderQtyVal) ? 0 : orderQtyVal;
I've always had to put null in the else conditions that don't have anything. Is there a way around it?
For example,
condition ? x = true : null;
Basically, is there a way to do the following?
condition ? x = true;
Now it shows up as a syntax error.
FYI, here is some real example code:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
This means several things:
use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:
condition && (x = true);
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
The last one will pass validation.
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
UPDATE
In relation to your sample, this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
No, it needs three operands. That's why they're called ternary operators.
However, for what you have as your example, you can do this:
if(condition) x = true;
Although it's safer to have braces if you need to add more than one statement in the future:
if(condition) { x = true; }
Edit: Now that you mention the actual code in which your question applies to:
if(!defaults.slideshowWidth)
{ defaults.slideshowWidth = obj.find('img').width()+'px'; }
More often, people use logical operators to shorten the statement syntax:
!defaults.slideshowWidth &&
(defaults.slideshowWidth = obj.find('img').width() + 'px');
But in your particular case the syntax can be even simpler:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width() + 'px';
This code will return the defaults.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.
See Short-Circuit Evaluation of logical operators for details.
var x = condition || null;
You could write
x = condition ? true : x;
So that x is unmodified when the condition is false.
This then is equivalent to
if (condition) x = true
EDIT:
!defaults.slideshowWidth
? defaults.slideshowWidth = obj.find('img').width()+'px'
: null
There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives
Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:
!defaults.slideshowWidth =
? defaults.slideshowWidth = obj.find('img').width()+'px'
: defaults.slideshowwidth
Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write
defaults.slideshowWidth = defaults.slideshowWidth
|| obj.find('img').width()+'px'
We also have now the "Nullish coalescing operator" (??). It works similar to the "OR" operator, but only returns the left expression if it's null or undefined, it doesn't return it for the other falsy values.
Example:
const color = undefined ?? 'black'; // color: 'black'
const color = '' ?? 'black'; // color: ''
const color = '#ABABAB' ?? 'black'; // color: '#ABABAB'
What about simply
if (condition) { code if condition = true };
To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():
const cond = false;
const arr = [
...(cond ? ['a'] : []),
'b',
];
// ['b']
And for objects:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
Original source
In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;
will become :
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
It's more clear, it's more "javascript" style.
You might consider using a guard expression instead (see Michael Thiessen's excellent article for more).
Let x be a logical expression, that you want to test, and z be the value you want to return, when x is true. You can then write:
y == x && z
If x is true, y evaluates to z. And if x is false, so is y.
The simple way to do this is:
if (y == x) z;
Why not writing a function to avoid the else condition?
Here is an example:
const when = (statement, text) => (statement) ? text : null;
const math = when(1 + 2 === 3, 'Math is correct');
const obj = when(typeof "Hello Word" === 'number', "Object is a string");
console.log(math);
console.log(obj);
You could also implement that function for any objects. Here is an example for the type string:
const when = (statement, text) => (statement) ? text : null;
String.prototype.if = when;
const msg = 'Hello World!';
const givenMsg = msg.if(msg.length > 0, 'There is a message! Yayyy!');
console.log(givenMsg);
Technically, it can return anything.
But, I would say for a one liner the Ternary is easier to type and at least 1 character shorter, so therefore faster.
passTest?hasDriversLicense=true:0
if(passTest)hasDriversLicense=true