How to check if value is number - angularjs

I have this function :
$scope.SearchTicketEvent = function (ticketPinOrEvent)
{
if (ticketPinOrEvent != undefined)
{
if (ticketPinOrEvent.length == 10)
{
$scope.PinTicketSearch(ticketPinOrEvent);
}
}
}
How can i check if ticketPinOrEvent is number ? I tried with angular.isNumber(ticketPinOrEvent) but i dont get anything?

If you want to use angular.isNumber
if ( !isNaN(ticketPinOrEvent) && angular.isNumber(+ticketPinOrEvent)) {
}

You might use the typeof to test if a variable is number.
if (typeof ticketPinOrEvent === 'number') {
$scope.PinTicketSearch(ticketPinOrEvent);
}
Or might try this:
if (!isNaN(ticketPinOrEvent) && angular.isNumber(ticketPinOrEvent)) {
$scope.PinTicketSearch(ticketPinOrEvent);
}
Testing against NaN:
NaN compares unequal (via ==, !=, ===, and !==) to any other value --
including to another NaN value. Use Number.isNaN() or isNaN() to most
clearly determine whether a value is NaN. Or perform a
self-comparison: NaN, and only NaN, will compare unequal to itself.

In Angular 6 this works without using any prefix.
Example:
if(isNumber(this.YourVariable)){
// your Code if number
}
else {
// Your code if not number
}

Related

React TypeScript - Why does Boolean() behave differently than double NOT (!!) operator when trying to conditionally render with && operator?

When working with javascript I always assumed that the double NOT operator (!!) behaves the same way as Boolean(), when trying to get a true / false out of a statement; however, since working with TypeScript I recently came across a scenario where they behaved differently, and I am trying to understand why that is. Take the following code for example:
import React from 'react'
interface Props {
myNumber: number | null
}
const Test: React.FC<Props> = ({ myNumber }) => {
return (
<>
{/* Example 1 */}
{!!myNumber && <span>{myNumber.toString()}</span>}
{/* Example 2 */}
{Boolean(myNumber) && <span>{myNumber.toString()}</span>}
</>
)
}
export default Test
Under example #1 the code works as I expect it: If the is rendered that means that myNumber passed the !! check, so it can never be null, thus myNumber.toString() will not return an error.
Under example #2 however, myNumber.toString() will return an error stating that "Object is possibly null", even though this code should only be reached if the Boolean(myNumber) returns true, and Boolean(null) should always be false.
Am I wrong thinking they should behave exactly the same? Is there something related to the TypeScrtipt compiler that I am missing? Thanks!
Boolean is typed as a function of type BooleanConstructor.
BooleanConstructor can be further broken down as <T>(value?: T | undefined) => boolean.
TypeScript does not consider the inner workings of a function when checking to see if a value may be null | undefined.
// Here TypeScript can directly infer that myNumber is indeed truthy
// by the preceeding double bang (!!) check.
const numberStrWithDoubleBang = !!myNumber && myNumber.toString();
// Here TypeScript cannot directly infer that myNumber is indeed truthy.
// To Typescript the function is a black box that takes in a number and
// returns a boolean, it does not know how the boolean value is calculated.
const numberStrWithFunction = isTruthy(myNumber) && myNumber.toString();
// While the isTruthy function above could easily have an implementation
// that does a simple truthy check on the passed in value as follows:
const isTruthy = <T>(value?: T | undefined) => !!value;
// It could also easily have an implementation with an output with no direct
// connection to the truthy status of the passed in value such as:
const isTruthy = <T>(value?: T | undefined) => {
const correctedValue = value ?? 0;
const midPoint = correctedValue / 2;
if (Math.random() * correctedValue > midPoint) {
return true;
}
return false;
};
At this point in time inferrence of null | undefined state via a function is considered to complex or the performance impact would be to great.
NOTE: !!0 and Boolean(0) are both false as 0 is a falsy value, if you need to get the string representation of zero you will need to update your checks.

onClick conditional rendering for three conditions

I have onClick that I want to hit a certain function depending on the following logic:
onClick={
approve && this.handleApproveClick,
!approve && !releaseHold && this.handleDeclineClick,
releaseHold && this.handleReleaseHoldClick
}
Oddly enough the last this.handleReleaseHoldClick works, while the others do not. What is the correct way to do this? Or do I really need to create a separate button?
Why does only the last work?
It's a basic comma operator case, where the "comma operator evaluates each of its operands (from left to right) and returns the value of the last operand".
What is the correct way to do this?
Since it's a triple-condition function, I'd suggest you to create a class method and simply secure each of possible cases.
handleSomeClick = () => {
if (approve) {
this.handleApproveClick();
} else if (!approve && !releaseHold) {
this.handleDeclineClick();
} else if (releaseHold) {
this.handleReleaseHoldClick();
}
}
and inside JSX:
onClick={this.handleSomeClick}

Why my OR Operator in angularjs is not working?

I am using a if condition in angularjs to check is a status is != Delivered or status is != Canceled then alert a message
if($scope.itemDeliveredStatus != "Canceled" || $scop.itemDeliveredStatus != "Delivered"))
{
alert("Please set item status to Delivered! or Canceled!");
return false;
}
Typo on the second condition, you put $scop instead of $scope :
$scop.itemDeliveredStatus
and an extra ) at the end of that line which is not necessary
First you do have a typo, but that is only one small issue. The other is a logic problem.
Your logic is wrong with the use of OR. Simple example below shows you that.
var foo = "A";
if (foo !== "A" || foo !== "B") {
console.log("WHY?")
}
Why? Because you are saying that in order for this if statement to be true, the variable foo has to be equal to two things.
You want it to say if foo does not equal A AND foo does not equal B, than show error.
var foo = "A";
if (foo !== "A" && foo !== "B") {
console.log("WHY?")
} else {
console.log("Better!!!")
}
So with the two issues fixed, your code would look like:
if ($scope.itemDeliveredStatus != "Canceled" && $scope.itemDeliveredStatus != "Delivered") { /*.. code */ }

sort an array of custom objects by Double property value with Swift 4

Im trying to move my self from objective-c to swift, I have a custom class named Market and this class contains some properties,
class Market {
var name = String?
var volume = Double?
}
lots of them stored in an Array and im trying to sort this Array ascending or descending by the volume property.
I tried this but is not working, Binary operator '>' cannot be applied to two 'Double?' operands
self.market.sort(by:{$0.volume > $1.volume})
whats the most convenient swift-way to do this?
Since volume is optional you can't compare the two value directly (except using ==). So you need to decide what it means to compare one missing volume value against either another missing volume value or against a valid volume value.
If you want to keep it simple, you could treat a missing volume value as zero. Then you code becomes:
self.market.sort { ($0.volume ?? 0) > ($1.volume ?? 0) }
A more complicated version would always sort nil volume values at the end:
self.market.sort {
if let v1 = $0.volume {
if let v2 = $1.volume {
// Both values exist
return v1 > v2
} else {
// there is no v2 - treat v1 as < v2
return false
}
} else {
if let v2 = $1.volume {
// there is no v1 - treat v2 as < v1
return true
} else {
// both are nil
return true
}
}
}
Since true will be returned if $0.volume is nil regardless of the value of $1.volume, that can be reduced to:
self.market.sort {
if let v1 = $0.volume {
if let v2 = $1.volume {
// Both values exist
return v1 > v2
} else {
// there is no v2 - treat v1 as < v2
return false
}
} else {
return true
}
}
Another option to consider is to avoid making your two properties optional. When parsing the JSON data, if either value is missing, simply skip that market since one could argue it isn't valid.
One of the possible ways.
Use ?? operator but be sure with validation of the volume.
self.market.sorted(by: {$0.volume ?? 0.0 > $1.volume ?? 0.0})
Or use default value for the class property.
var volume: Double? = 0.0

AngularJS Nested IF

I'm trying to add a bit of logic to my controller with a couple of nested If statements. By themselves they work fine, but after nesting them, i'm not getting any results.
This is a working statement:
if (typeof object["Frequency"]!='undefined' && object["Frequency"]=='yearly' && ('now' <= 'upcoming')) {
$scope.summary[segment].totalLateRelationships++;
$scope.summary[segment].lateRelationships.push(object);
}
This is working:
if (!(object["nextmeetingowner"].length) || !(object["nextmeetingowner"].length) ) {
$scope.summary[segment].totalLateRelationships++;
$scope.summary[segment].lateRelationships.push(object);
}
This is what I'm trying to accomplish:
if (!(object["primaryaccountability"].length) || (!(object["nextmeetingowner"].length))) {
if (typeof object["Frequency"]!='undefined' && object["Frequency"]=='yearly' && ('now' <= 'upcoming'))
{
$scope.summary[segment].totalLateRelationships++;
$scope.summary[segment].lateRelationships.push(object);
}
}
That third code block is checking something different than the first two. It's evaluating
!(object["primaryaccountability"].length)
...whereas the earlier code is evaluating
!(object["Last Meeting Date"].length)

Resources