Number palindromes code not working - javascript

Ive been doing the 'Numerical Palindrome #1' Kata in codewars and I feel like this code should work, but its saying that palindrome(1221) is coming back as false - when obviously it should be coming back as true. if anyone can see why this would be happening i would greatly appreciate it! the challenge said that if num was less than 0, or wasnt an integer then it should return 'not valid'.
function palindrome(num) {
if(typeof num == 'number'){
if(Number.isInteger(num) && num>=0){
return(toString(num) === toString(num).split('').reverse().join(''));
}
else{return 'Not valid';
}
}
else { return 'Not valid';
}
}

toString is a method of Number.prototype so you call it from the number:
function palindrome(num) {
if (typeof num == 'number') {
if (Number.isInteger(num) && num >= 0) {
return (num.toString() === num.toString().split('').reverse().join(''));
} else {
return 'Not valid';
}
} else {
return 'Not valid';
}
}
console.log(palindrome(500))
console.log(palindrome(505))

There was some problem with your code.
you need to use toString() like below :
num.toString()
and also you don't need two if for checking your conditions, you can do it with only 1 if.
I update your code :
var a = function palindrome(num) {
if(typeof num == 'number' && Number.isInteger(num) && num>=0)
return(num.toString() === num.toString().split('').reverse().join(''));
else
return 'Not valid';
}
console.log(a(1001));
https://jsfiddle.net/emilvr/qkz5ypq9/

toString method that you are using will return toString(123456) = "[object Undefined]" . & toString(123456).split('').reverse().join('') = "]denifednU tcejbo[" and hence it is failing. to convert a number to string best is to concatenate it with "", like 12345+"";

You should use String instead of toString.
function palindrome(num) {
if (typeof num == 'number' && Number.isInteger(num) && num >= 0) {
return (String(num) === String(num).split('').reverse().join(''));
}
return 'Not valid';
}

Related

Can anyone tell me why I get a error when i try to call this function?

<!doctype html>
<html>
<script>
function isNumber(value) {
return typeof (value) != "boolean" && !isNaN(value) && value.length > 0;
}
function minMaxDefrost(value, min, max) {
if (value.length == 0 || value == "-") return value;
if (!isNumber(value)) return value.substring(0, value.length - 1);
console.log("minMaxDefrost called ")
if (parseFloat(value) < min){
return min;
}
else if (parseFloat(value) > max){
return max;
}
else {
return Math.floor(value);
}
}
minMaxDefrost(4, 0, 12);
</script>
</html>
I use this function in a html keyup function and it works fine but when i try to call it by itself at the start of the code i get the error message Uncaught TypeError: value.substring is not a function
also not when i call this function from the keyup i use "this.value = minMaxDefrost(this.value, -80, 150, 0)
im assuming the error has got to do with the this.value but i dont know how to fix it
isNumber doesn't exactly do its job as Mark Hanna suggests.. a better isNumber would be something like
function isNumber(num){
let num1=num-0, num2=num-1
return num2!=num1 && !!(num2||num1) && typeof(num)!="object"
//Infinity would fail the test num2!=num1
//Normal non-numbers would fail !!(num2||num1)
//null would fail typeof(null)!="object"
//However, 0, and even "0" will pass this test
}
Here is it returned in the code you gave us
function isNumber(num){
let num1=num-0, num2=num-1
return num2!=num1 && !!(num2||num1) && typeof(num)!="object"
//Infinity would fail the test num2!=num1
//Normal non-numbers would fail !!(num2||num1)
//null would fail typeof(null)!="object"
//However, 0, and even "0" will pass this test
}
function minMaxDefrost(value, min, max) {
if (value.length == 0 || value == "-") return value;
if (!isNumber(value)) return value.substring(0, value.length - 1);
console.log("minMaxDefrost called ")
if (parseFloat(value) < min){
return min;
}
else if (parseFloat(value) > max){
return max;
}
else {
return Math.floor(value);
}
}
minMaxDefrost(4, 0, 12);
isNumber(4) evaluates to false, so you're trying to call a substring method on 4 but that doesn't exist. Use typeof value === 'number' instead to test if something is a number. Or better yet, use typeof value === 'string' before treating it like it's definitely a string.

String validation function in JavaScript

I'm trying to create a nice util function to validate strings. Conditions are:
Cannot be typeof "undefined"
Cannot be null
Must be a string i.e. not a number, object, array, etc.
Must have at least one character in it. So a string with value of '' would be invalid.
I found some pointers on this that suggest using RegEx is the way to do it but the following is not working when I give it a numeric value.
Here's what I have so far:
const isValidString = (str1) => {
if(typeof str1 === "undefined" || str1 === null) return false;
const validRegEx = /^[^\\\/&]*$/;
if(str1.match(validRegEx)) {
return true;
} else {
return false;
}
}
As I said, if send const str1 = 3; to this function, I get an error that reads:
"TypeError: badString.match is not a function
What am I missing?
if (str1 != null) will coerce the str1 value, and will check both against null and undefined.
EDIT: ignore this part (Also, you don't need to use a regex to check if there's at least one character. You can use the string length. str1.length will evaluate to a falsey value if it's 0, otherwise it will evaluate to a truethy value.) You need a strict boolean value, so it should be str1.length > 0.
function isValidString(str1) {
return str1 != null && typeof str1 === "string" && str1.length > 0;
}
Why don't you add a typeof str1 === 'string' as shown below
if(typeof str1 === 'string' && str1.match(validRegEx)) {
return true;
} else {
return false;
}
That is because the match method is only available on strings, and you are attempting to call it on a number.
I would suggest re-writing the function to ensure that the argument is a string, rather than only checking for null or undefined values:
const isValidString = str1 => {
if (!str1 || typeof str1 !== 'string') return false
const validRegEx = /^[^\\\/&]*$/
if (str1.match(validRegEx)) {
return true
} else {
return false
}
}
Convert number to string perform evaluating it
const isValidString = (str1) => {
str1 = str1.toString();
if(typeof str1 === "undefined" || str1 === null) return false;
const validRegEx = /^[^\\\/&]*$/;
if(str1.match(validRegEx)) {
return true;
} else {
return false;
}
}
console.log(isValidString(3))
Replace the if with following:
if(typeof str1 === "undefined" || str1 === null || typeof str1 !== 'string') return false;
Use RegExp#test instead, because your regular expression will always be available. Also, String#match returns an array (or null) which is not well-suited for boolean expressions and may produce unwanted results.
const isValidString = (str1) => {
if (typeof str1 === "undefined" || str1 === null) return false;
const validRegEx = /^[^\\\/&]*$/;
if (validRegEx.test(str1)) {
return true;
} else {
return false;
}
}
console.log(isValidString(1));
console.log(isValidString('string'));
Note, your regexp is still wrong because it validates the number as true. You need to tweak it more.
Credit to djfdev on this one, all I've really done is simplify his answer to be more succinct.
const isValidString = str1 => {
return typeof str1 === 'string' && /^[^\\\/&]*$/.test(str1);
}

How to catch null, undefined, blank values with AngularJS filter

I'm attempting to write a filter for use in a grid that will catch all null, undefined, blank string, or other similar values and display a dash "-". I've written the following so far, but it doesn't catch null values, and I'm wondering if it could be more succinct and possibly refactored to avoid three layers of nested if/else statements. Percentage values need to be checked that they're over 0 and under 1. Also, negative numbers and 0's should be returned as is. Thanks!
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (cellFilter == undefined) {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
}
}
};
});
Version 2.0 taking into account #tymeJV's comment:
angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
return function (input, cellFilter, args1, args2) {
if (!cellFilter) {
return (angular.isNumber(input) || (input)) ? input : '-';
} else {
if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
} else {
return (angular.isNumber(input) || (input)) ? $filter(cellFilter)(input, args1, args2) : '-';
}
}
};
});
Whenever you encounter a function that's getting too complex to refactor try extracting some of the smaller statements to concisely named variables. It makes it much easier for our brains to keep track of the function's requirements, and it's also more readable to new devs reading your code.
var inputHasValue = angular.isNumber(input) || input;
if(!inputHasValue){
return '-';
}
if (!cellFilter) {
return input;
}
var isPercentageCell = cellFilter.match(/pctg|percent|pctgFilter|incidence/ig);
var valueIsInRange = input > 0 && input < 1;
if(!isPercentageCell || valueIsInRange){
return $filter(cellFilter)(input, args1, args2);
}
return '-';
typeof x ==='number' || !!x
is false when x is null, undefined or empty string
Only one case in which it doesn't work – if you need to filter boolean variables, but your case doesn't seem to need it.
Anyway in that case you can use
typeof x === 'boolean' || typeof x ==='number' || !!x

How can I make a function to check if a parameter is a number and have it accept an undefined parameter?

I have the following function:
isNumber: function (num) {
// Return false if num is null or an empty string
if (num === null || (typeof num === "string" && num.length === 0)) {
return false;
}
var rtn = !isNaN(num)
return rtn;
},
This gives me a problem if num is not yet defined. How can I make it return false when num is undefined?
You could use "loose" comparison when you compare against null:
num == null
This will be true if num is undefined or null (and only then).
You can also simplify the string comparison so that the overall test is:
num == null || num === ''
Replace
if (num === null || (typeof num === "string" && num.length === 0))
with
if (num === null || typeof num === "undefined" || (typeof num === "string" && num.length === 0))
as you see, the new condition also handles the case in which num is undefined.
See this answer.
<script>
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
alert(isNumber()); //false
alert(isNumber(10)); //true
alert(isNumber(null)); //false
alert(isNumber(undefined)); //false
</script>
You can check if no value was passed to the function by testing the array of the arguments passed to the function; so if arguments.length=0 then no arguments were passed to the function and num will not be defined.
You could also do further checks against num !== undefined && num !== null (note that non-identity operator !== is used instead of non-equality operator !=).
Instead you could just check that if you parse the number it is a valid non-infinite number:
isNumber: function (num) {
if ( arguments.length == 0 )
{
return false;
}
return !isNaN(parseFloat(num))&&isFinite(num);
}
This checks if:
parseFloat(num) evaluates to a valid number; and if
isFinite(num) - that valid number is not positive or negative infinity.
If this meets your criteria then you don't need the first check (since parseFloat(undefined) returns NaN) and can simplify the function to:
isNumber: function (num) {
return !isNaN(parseFloat(num))&&isFinite(num);
}

How do I check if a string is NOT a floating number?

var num = "10.00";
if(!parseFloat(num)>=0)
{
alert("NaN");
}
else
{
alert("Number");
}
I want to check if a value is not a float number, but the above code always returns NaN, any ideas what I am doing wrong?
!parseFloat(num) is false so you are comparing false >= 0
You could do this:
if(! (parseFloat(num)>=0))
But it would be more readable to do this:
if(parseFloat(num) < 0)
parseFloat returns either a float or NaN, but you are applying the Boolean NOT operator ! to it and then comparing it to another floating point.
You probably want something more like:
var num = "10.0";
var notANumber = isNaN(parseFloat(num));
Because ! has a higher precedence than >=, so your code does
!parseFloat(num) which is false
Then
>= 0, false is coerced into 0, and 0 >= 0 is true, thus the alert("NaN")
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
function isFloat(value) {
if(!val || (typeof val != "string" || val.constructor != String)) {
return(false);
}
var isNumber = !isNaN(new Number(val));
if(isNumber) {
if(val.indexOf('.') != -1) {
return(true);
} else {
return(false);
}
} else {
return(false);
}
}
ref

Categories

Resources