In continuing my question from yesterday, I have the following code:
function VAL(str) {
// IF LEFT(str,1) IN('0,1,2,3,4,5,6,7,8,9,.) THEN
return parseFloat(str);
return 0;
}
function LEFT(str,n) {
if (n <= 0) return "";
if (n >= str.length) return str;
return str.substring(0,n);
}
Q: How do I write the commented line above such that it says "IF the first character is 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or period, then return parseFloat(str)"?
You don't need that check. If the first character is not a digit, then parseFloat returns NaN.
function VAL(str) {
var f = parseFloat(str);
return isNaN(f) ? 0 : f;
}
I would use Regex
if (str.match(/([0-9]|\./)) return parseFloat(str);
set = "0123456789";
if (set.indexOf(LEFT(str, 1)) > -1 return parseFloat(str);
Related
I'm working on a codewars problem-here's the question:
-Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value.
-Division by zero should return NaN.
I have the first part figured out, but how do I return NaN if I divide by 0? I don't know a lot about NaN and I'm pretty new to JavaScript.
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return undefined;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return undefined;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}
Edit: solved, answer is below
Welcome to our community!
NaN stands for Not-a-Number and it is a property of the global object(in order to understand more about the global object, I would recommend reading about Scopes).
You could access NaN like this:
window.NaN => from a browser
Number.NaN
NaN
If you want to check if a number is NaN you could use: isNaN.
If you want to use it in a function you can just do
function test(x){
if(isNaN(x)){
return NaN;
}
return x;
}
To come back to your problem, you could do something like this:
function calculateRemainder(a,b){
return a>b ? a % b : b % a
}
Where % is known as the remainder operator about which you can read more here. This operator returns NaN if you try to divide by 0 or to operate with Infinity.
The following operations return NaN:
NaN % 2
Infinity % 0
10 % 0
Infinity % Infinity
The problem is that % is not the divider syntax, but this is /.
I created a basic example for you:
In this example, the console logs "divider is 0"
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 0);
But here, it will log 2.5
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 2);
This is my answer (with help from the comments on my question), and it worked. Thank you for your help!
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return NaN;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return NaN;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
leetcode question
"cc" // -1
"ccdd" // -1
"leetcode" // 1
"loveleetcode" // 2
"abcabd" // 2
"thedailybyte" // 1
"developer" // 0
My approach passed all the test cases except the 2nd test case "ccdd". I am expecting -1 but receiving 4. Not sure why.
var firstUniqChar = function(s) {
if(!s || s.length === 0 ) return -1
else if(s.length === 1) return 0
let pointer1 = 0
let pointer2 = pointer1 + 1
if(s.length > 2){
while(pointer2 <= s.length - 1){
if(s[pointer1] !== s[pointer2])
pointer2++
else if(s[pointer1] === s[pointer2])
pointer1++
}
return pointer1
}
return -1
};
this is too old, but still can be too much shorter:
const firstUniqChar = (_str) => {
for (let i= 0; i < _str.length; i+= 1) {
if (_str.indexOf(_str[i]) === _str.lastIndexOf(_str[i])) return i+1;
}
return -1;
}
How do you check whether or not an integer contains a digit?
For example:
var n = 12;
var m = 34;
n contains 1 // true
m contains 1 // false
What's the fastest (performance wise) way to do this without turning the integer into a string?
Refer to the following code (if the comments aren't good enough feel free to ask):
function contains(number, digit) {
if (number < 0) { // make sure negatives are dealt with properly, alternatively replace this if statement with number = Math.abs(number)
number *= -1;
}
if (number == digit) { // this is to deal with the number=0, digit=0 edge case
return true;
}
while (number != 0) { // stop once all digits are cut off
if (number % 10 == digit) { // check if the last digit matches
return true;
}
number = Math.floor(number / 10); // cut off the last digit
}
return false;
}
Here's a simple recursive form -
const contains = (q, p) =>
p < 10
? p === q
: p % 10 === q || contains(q, p / 10 >>> 0)
console.log(contains(1, 12)) // true
console.log(contains(1, 34)) // false
console.log(contains(9, 14293)) // true
console.log(contains(9, 1212560283)) // false
if (n.toString().includes("1")) {
/// Do something
}
try this:
let n = 1234;
let flag = false;
while (n > 0){
r = n % 10;
if(r == 1){
flag = true;
break;
}
n = (n - (n % 10)) / 10;
}
console.log("n contains 1 = "+flag);
So this function makes it possible to get an alphabet character or multiple depending on what number you send in. I want to reverse this function so that when I send in the character, I receive a number. I have been able to achieve this with single letters.
I have already created an alphabetic id system by first generating a number then converting it into a letter in the alphabet using this id as the index. But what I want to do is after 26 characters have been used i would like for it to continue with AA, AB, AC and so on.
EDIT: I want to clarify that my thought was that the converter should extend beyond
A-series. So after AZ it goes to BA BB.. BZ, CA CB CC and so on.
Also what i want get return is a number and not the letter. The original function gives me the letters, now I need to reverse it to get back the number i sent in the previous function
function convertNumberToId (number) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if (number < alphabet.length) {
return alphabet[number];
} else {
return (
convertNumberToId(Math.floor(number / alphabet.length) - 1)
+
convertNumberToId(number % alphabet.length)
);
}
}
In the if statement you get a letter back if the number does not exceed the length of the array but once it does you'll get AA, AB, AC and so on. Now I want to reverse this.
This is what I have achieved so far:
function convertIdToNumber(id){
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if($.inArray(id , alphabet) !== -1){
return alphabet.indexOf(id);
}
else{
}
}
REVISED (Start at 0 Index)
Now we calculate value from right to left. As you move to the left, the value of the character is multiplied by the length of the alphabet raised to the number of digits you've moved left. Handle offset of 1.
function convertNumberToId (number) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if (number < alphabet.length) {
return alphabet[number];
} else {
return (
convertNumberToId(Math.floor(number / alphabet.length) - 1)
+
convertNumberToId(number % alphabet.length)
);
}
}
function convertIdToNumber(id){
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if(id.length == 1){
return alphabet.indexOf(id) >= 0 ? alphabet.indexOf(id) : -1;
}
else if (id.length > 0){
let t = 0;
for (let i = 0; i < id.length; i++) {
t += (1 + convertIdToNumber(id.charAt(id.length - 1 - i))) * Math.pow(alphabet.length, i);
}
t--;
return t;
} else {
return -1;
}
}
console.log(convertIdToNumber('b'));
console.log(convertNumberToId(1));
console.log(convertIdToNumber('abc'));
console.log(convertNumberToId(730));
Find the value of each character in the id, add the length of the alphabet for each additional character, and handle the offset of 1 when you have multiple characters.
Start at index 0
function convertIdToNumber(id){
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if(id.length == 1){
return alphabet.indexOf(id);
}
else if (id.length > 0) {
return convertIdToNumber(id.split('')[0])
+ alphabet.length
+ convertIdToNumber(id.slice(1))
+ 1;
} else {
return -1;
}
}
console.log(convertIdToNumber('ac'));
Start at index 1
function convertIdToNumber(id){
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if(id.length == 1){
return alphabet.indexOf(id) >= 0 ? alphabet.indexOf(id) + 1 : -1;
}
else if (id.length > 0) {
return convertIdToNumber(id.split('')[0])
+ alphabet.length
+ convertIdToNumber(id.slice(1))
- 1;
} else {
return -1;
}
}
console.log(convertIdToNumber('ac'));
function convertIdToNumber(id){
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if ($.inArray(id , alphabet) !== -1){
// Can remove the add one here if you want 'a' = 0
return alphabet.indexOf(id) + 1;
} else {
return (Math.pow(26, id.length - 1) * (alphabet.indexOf(id.charAt(0)) + 1)) + convertIdToNumber(id.slice(1));
}
}
console.log(convertIdToNumber("aa")); // 27
console.log(convertIdToNumber("ab")); // 28
console.log(convertIdToNumber("ac")); // 29
console.log(convertIdToNumber("zz")); // 702
console.log(convertIdToNumber("abc")); // 731
JQuery live demo: https://jsfiddle.net/chkt65n7/5/
I used your original function but I assumed "a" in this case was 1 as you mentioned "aa" was 27 but if that part is different then you can minus the one from the ending recursive case if you want.
Revised to handle more than 2 characters in a string
Have the function DashInsert(num) insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
Here is my code (not working). When I run it, I get the same response as an infinite loop where I have to kill the page but I can't see why. I know there are ways to do this by keeping it as a string but now I'm wondering why my way isn't working. Thanks...
function DashInsert(num) {
num = num.split("");
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
num.splice(i, 0, "-");
}
}
num = num.join("");
return num;
}
Using num.splice you are inserting new entries into the array, therefor increasing its length – and that makes the value of i “running behind” the increasing length of the array, so the break condition is never met.
And apart from that, on the next iteration after inserting a -, num[i-1] will be that - character, and therefor you are practically trying to check if '-' % 2 != 0 … that makes little sense as well.
So, when you insert a - into the array, you have to increase i by one as well – that will a) account for the length of the array having increased by one, and also it will check the next digit after the - on the next iteration:
function DashInsert(num) {
num = num.split("");
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
num.splice(i, 0, "-");
i++; // <- this is the IMPORTANT part!
}
}
num = num.join("");
return num;
}
alert(DashInsert("454793"));
http://jsfiddle.net/37wA9/
Once you insert a dash -, the if statement is checking this '-'%2 != 0 which is always true and thus inserts another dash, ad infinitum.
Here's one way to do it with replace using a regex and function:
function DashInsert(n) {
var f = function(m,i,s) { return m&s[i+1]&1 ? m+'-' : m; };
return String(n).replace(/\d/g,f);
}
DashInsert(454793) // "4547-9-3"
When you are adding a dash, this dash will be processed as a number on the next iteration. You need to forward one step.
function DashInsert(num) {
var num = num.split("");
for (var i = 1; i < num.length; i++) {
if ((num[i - 1] % 2 != 0) && (num[i] % 2 != 0)) {
num.splice(i, 0, "-");
i++; // This is the only thing that needs changing
}
}
num = num.join("");
return num;
}
It's because there are cases when you use the % operator on dash '-' itself, e.g. right after you splice a dash into the array.
You can correct this behavior by using a clone array.
function DashInsert(num) {
num = num.split("");
var clone = num.slice(0);
var offset = 0;
for (i = 1; i < num.length; i++) {
if (num[i - 1] % 2 != 0 && num[i] % 2 != 0) {
clone.splice(i + offset, 0, "-");
offset++;
}
}
return clone.join("");
}
alert(DashInsert("45739"));
Output: 45-7-3-9
Demo: http://jsfiddle.net/262Bf/
To complement the great answers already given, I would like to share an alternative implementation, that doesn't modify arrays in-place:
function DashInsert(num) {
var characters = num.split("");
var numbers = characters.map(function(chr) {
return parseInt(chr, 10);
});
var withDashes = numbers.reduce(function(result, current) {
var lastNumber = result[result.length - 1];
if(lastNumber == null || current % 2 === 0 || lastNumber % 2 === 0) {
return result.concat(current);
} else {
return result.concat("-", current);
}
}, []);
return withDashes.join("");
}
It's longer, but IMHO reveals the intention better, and avoids the original issue.