Extract non-negative number from the ending of a string in js - javascript

Just like the title says
Description of the example:
x) example string -> what I need as the output
examples:
1) "asdf" -> null or -1 or undefined (because nothing was found)
2) "asdf1" -> 1
3) "asdf0" -> 0
4) "asdf-1" -> 1
5) "asdf001" -> 1
6) "asdf1234" -> 1234
7) "asdf12.34" -> 34 (ending value, so number after .)
8) "123asdf78" -> 78 (integer from ending)
I hope these examples will be enough. I tried doing this with for loop, but it didn't work out. Does anyone know if there are functions which enable to do something like this or similar?
More info about my approach:
In the for loop I checked for every character if is >= '0' && <= '9' then added to previous tmp variable which responsible for concatenate all characters, and at the end I parsed this to int. But I think this solution is bad...

You can use simple regular expression for this purpose:
function numericSuffix(string) {
const match = string.match(/\d+$/);
return match !== null ? Number(match[0]) : null;
}
numericSuffix('abc-123') // 123
numericSuffix('abc-123x') // null

Related

How to find a string with specific letters in gethash javascript function

function getHash( string ) {
let h = 7, letters = "acdefhlmnoprstuw";
for( var i = 0; i < string.length; i++ ) {
h = ( h * 37 + letters.indexOf( string[ i ] ) );
}
return h;
}
My task is to write a code which finds the string containing some of following letters: ACDEFHLMNOPRSTUW
Sothat the function getHash(THE SEARCHING STRING) gets the result of 18794359164.
I am not giving you some code, just some hints.
To get an understanding of the code, you have, and the one, you want to get, is to take a string with you gunction and get a hash value from it.
For example take 'wonder' and get
19017519751
as hash value.
This value contains a start value of seven (h = 7) and for each letter it multiplies h with 37 (this value looks like it is made for 37 different characters) and adds the index value of letters.
To get the opposite with a numerical value, you need to separate a rest of a division by 37 to get an index of a letter, exact the opposite of using a letter and add a value to the hash.
For example take the above value 19017519751 and get the rest of the division by 37
19017519751 % 37 -> 11 r
Now with the last letter (remember encoding goes from start to end of the word, decoding starts with the end), you need get a value without the last letter.
By encoding, you multiply each last sum by 37 and this works here as well, but in reversed manner and you need an integer value. Just divide by 37 and take the floored value for the next letter.
The rest looks like this:
513987020 % 37 -> 3 e
13891541 % 37 -> 2 d
375447 % 37 -> 8 n
10147 % 37 -> 9 o
274 % 37 -> 15 w
Finially, you need to have a check to stop the iteration ans this value is 7 the first value of encoding.

Check length between two characters in a string

So I've been working on this coding challenge for about a day now and I still feel like I haven't scratched the surface even though it's suppose to be Easy. The problem asks us to take a string parameter and if there are exactly 3 characters (not including spaces) in between the letters 'a' and 'b', it should be true.
Example: Input: "maple bread"; Output: false // Because there are > 3 places
Input: "age bad"; Output: true // Exactly three places in between 'a' and 'b'
Here is what I've written, although it is unfinished and most likely in the wrong direction:
function challengeOne(str) {
let places = 0;
for (let i=0; i < str.length; i++) {
if (str[i] != 'a') {
places++
} else if (str[i] === 'b'){
}
}
console.log(places)
}
So my idea was to start counting places after the letter 'a' until it gets to 'b', then it would return the amount of places. I would then start another flow where if 'places' > 3, return false or if 'places' === 3, then return true.
However, attempting the first flow only returns the total count for places that aren't 'a'. I'm using console.log instead of return to test if it works or not.
I'm only looking for a push in the right direction and if there is a method I might be missing or if there are other examples similar to this. I feel like the solution is pretty simple yet I can't seem to grasp it.
Edit:
I took a break from this challenge just so I could look at it from fresh eyes and I was able to solve it quickly! I looked through everyone's suggestions and applied it until I found the solution. Here is the new code that worked:
function challengeOne(str) {
// code goes here
str = str.replace(/ /g, '')
let count = Math.abs(str.lastIndexOf('a')-str.lastIndexOf('b'));
if (count === 3) {
return true
} else return false
}
Thank you for all your input!
Here's a more efficient approach - simply find the indexes of the letter a and b and check whether the absolute value of subtracting the two is 4 (since indexes are 0 indexed):
function challengeOne(str) {
return Math.abs(str.indexOf("a") - str.indexOf("b")) == 4;
}
console.log(challengeOne("age bad"));
console.log(challengeOne("maple bread"));
if there are exactly 3 characters (not including spaces)
Simply remove all spaces via String#replace, then perform the check:
function challengeOne(str) {
return str = str.replace(/ /g, ''), Math.abs(str.indexOf("a") - str.indexOf("b")) == 4;
}
console.log(challengeOne("age bad"));
console.log(challengeOne("maple bread"));
References:
Math#abs
String#indexOf
Here is another approach: This one excludes spaces as in the OP, so the output reflects that. If it is to include spaces, that line could be removed.
function challengeOne(str) {
//strip spaces
str = str.replace(/\s/g, '');
//take just the in between chars
let extract = str.match(/a(.*)b/).pop();
return extract.length == 3
}
console.log(challengeOne('maple bread'));
console.log(challengeOne('age bad'));
You can go recursive:
Check if the string starts with 'a' and ends with 'b' and check the length
Continue by cutting the string either left or right (or both) until there are 3 characters in between or the string is empty.
Examples:
maple bread
aple brea
aple bre
aple br
aple b
ple
le
FALSE
age bad
age ba
age b
TRUE
const check = (x, y, z) => str => {
const exec = s => {
const xb = s.startsWith(x);
const yb = s.endsWith(y);
return ( !s ? false
: xb && yb && s.length === z + 2 ? true
: xb && yb ? exec(s.slice(1, -1))
: xb ? exec(s.slice(0, -1))
: exec(s.slice(1)));
};
return exec(str);
}
const challenge = check('a', 'b', 3);
console.log(`
challenge("maple bread"): ${challenge("maple bread")}
challenge("age bad"): ${challenge("age bad")}
challenge("aabab"): ${challenge("aabab")}
`)
I assume spaces are counted and your examples seem to indicate this, although your question says otherwise. If so, here's a push that should be helpful. You're right, there are JavaScript methods for strings, including one that should help you find the index (location) of the a and b within the given string.
Try here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods

How does this work in C++ and any rough equiavalnce of this in JavaScript?

I am currently working on an encryption/decryption program written in C++. There is a snippet in the code which I have not understood. I have been trying to convert entire source into JavaScript.
I have two questions:
How does this code work? I am very new to C++ programming.
Any rough equivalence of this in JavaScript?
uint32_t char_to_int(char c){
if(c >='0' && c<='9')
return c -'0';
else
return c - 'a' + 10;
}
1) How does this code work?
uint32_t char_to_int(char c){
if(c >='0' && c<='9')
return c -'0';
else
return c - 'a' + 10;
}
that just return the integer value 0 .. 15 from an hexadecimal digit '0' .. '9' or 'a' .. 'f'
if c is the character '3' the first test is true so it returns '3' - '0' = 3
if c is the character 'b' the test is false and the code returns 'b' - 'a' + 10 = 11
2) Any rough equivalence of this in JavaScript?
in javascript just use parseInt(hexString, 16);
If I complete the given code to be able to use it :
#include <iostream>
typedef unsigned uint32_t;
uint32_t char_to_int(char c) {
if(c >='0' && c<='9')
return c -'0';
else
return c - 'a' + 10;
}
int main()
{
for (char c = '0'; c <= '9'; ++c)
std::cout << c << " -> " << char_to_int(c) << std::endl;
for (char c = 'a'; c <= 'f'; ++c)
std::cout << c << " -> " << char_to_int(c) << std::endl;
return 0;
}
The execution is :
0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
6 -> 6
7 -> 7
8 -> 8
9 -> 9
a -> 10
b -> 11
c -> 12
d -> 13
e -> 14
f -> 15
uint32_t char_to_int(char c){
if(c >='0' && c<='9')
return c -'0';
else
return c - 'a' + 10;
}
This function converts digits ('0' to '9'), to their numeric equivalent i.e. '0' is converted to 0, '1' is converted to 1, .... '9' is converted to 9.
The c - 'a' + 10, converts lower case letters to a numeric equivalent viz 'a' becomes 10, 'b' becomes 11, ..... 'z' becomes 35. However, this ONLY works if the implementation (i.e. compiler) uses a character set with a contiguous set of lower-case letters (like ASCII). There are real-world character sets that do not have a contiguous set of lower-case letters though.
The problem is that conversion is also done for all characters, other than digits, and the result is then probably meaningless. For example, it will not correctly handle uppercase letters (if one expects uppercase letters to be converted to the same as their lowercase equivalents).
The function operates on one character at a time. It attempts to do the same thing as the standard function strtoul() except, except that strtoul() (1) works on a string (not a single character), (2) works correctly for both upper and lower case letters, (3) will work correctly regardless of what character set the implementation supports, and (4) does error checking (e.g. returning zero if an invalid character is detected). strtoul() is not limited to hex conversion - it works up to base 35.
As to an equivalent in JavaScript - essentially the same code will probably work, but with flaws similar to those in the C/C++ version.
In C++, char is an integral type like int. A character literal, like 'a' or '0', is of an integral type too, and not a string like in JavaScript.
In JavaScript, you would get such an integral value (character code) by using s.charCodeAt(0) to your one-character string s. For longer strings, it will return the character code of the first character.
The table of codes for the base character set for the predominantly using encodings can be found here.
Directly converting your C++ code to JavaScript can be pretty straightforward just by adding the missing .charCodeAt(0) to the variable and to the string literals.
Also bear in mind that '1' - '0' in C++ is not the same as '1' - '0' in JavaScript, although the results are the same. The former subtracts a character code of '0' from a character code of '1'. The latter converts '1' to 1, '0' to 0, and calculates the difference. That's why you are receiving NaN with c - 'a', where 'a' (and probably c) is not convertible to a number.

When should you use parentheses inside an if statement's condition?

I have a if condition like so:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( name == 'Stack' && lastname == 'Overflow' )
alert('Hi Stacker!');
});
So my alert is fired...
If I put my condition inside a brackets like this:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( (name == 'Stack') && (lastname == 'Overflow') ){
alert('Hi Stacker!');
}
});
My alert is also fired...
My question is: When and why I should use parentheses inside my if condition? Thank you!
There is no much difference in your example.
You can read that for reference
Operator Precedence (JavaScript)
You use it to force associations, in your example this won't change anything. But consider this case:
A and B or C
is a lot different from
A and (B or C)
Here you would be preventing the expression from being understood as (A and B) or C which is the natural way javascript and maths do things.
Because of operator precedence :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
you'd better read this if you want more details
But basically == (equality) weights more than && (logical-and) , so A == B is evaluated before C && D given
C <- A == B
and
D <- E == F
so adding parenthesis to C or D dont matter,in that specific situation.
Brackets can be used, if multiple conditions needs to be checked.
For ex: User is also a Stacker if full name is 'StackOverflow' then add another condition with 'Or' operator.
if(((name == 'Stack') && (lastname == 'Overflow')) || FullName =='StackOverflow')
As you can see, name and last name are placed inside one bracket meaning that it gives a result either true or false and then it does OR operation with FullName condition.
And having brackets around name, lastname and fullname fields are optional since it doesn't make any difference to the condition. But if you are checking other condition with FullName then group them into bracket.
Brackets are never required in such situations.
Of course, try to read first solution (without) and second solution (with). Second one it's clear, fast-readable and easy to mantain.
Of course if you have to change precedence (in this case you just have an AND condition, but what if you need and AND and an OR? 1 and 2 or 3 priority changes between "(1 and 2) or 3" - "1 and (2 or 3)"
Brackets () are used to group statements.
Ex - if you have an expression '2 + 3 * 5'.
There are two ways of reading this: (2+3)*5 or 2+(3*5).
To get the correct o/p based on operator precedence, you have to group the correct expression like * has higher precedence over +, so the correct one will be 2+(3*5).
first bracket requires for complex condition to ensure operator precedence correctly. lets say a example
var x=1,y=1,z=0;
if(x==0 && y==1 || z==0)
{
//always true for any value of x
}
what will happen here
(0 && 1 ||1) ----> (0 ||1)----->1
&& has high precedence over ||
if(x==0 && (y==1 || z==0)) alert('1');
{
//correct way
}
if you do not use (y==1 || z==0) bracket the condition always will be true for any value of x.
but if you use (..) the condition return correct result.
Conditional statements can be grouped together using parenthesis. And is not only limited to if statements. You can run the example below in your Chrome Developer Tools.
Example 1:
Console Execution
false && false || true
// true
flow
false && false || true
| | |
|________| |
| |
| |
false or true
| |
|_________________|
|
|
true
Example 2:
Console Execution
false && (false || true)
// false
flow
false && (false || true)
| |
|______________|
|
|
false
Helpful resources for playing around with JSInterpreter and AST's:
https://neil.fraser.name/software/JS-Interpreter/
https://esprima.org/demo/parse.html#
Consider the statement
if( i==10 || j == 11 && k == 12 || l == 13)
what you would want is if either i is 10 or j is 11 And either k is 12 or l is 13 then the result shouldbe true, but say if i is 10, j is 11, k is 10 and l is 13 the condition will fail, because the fate of equation is decided at k as aoon as && comes in picture. Now if you dont want this to happen the put it like this
if( (i==10 || j == 11) && (k == 12 || l == 13))
In this ORs will be executed first and the result will be true.

Number equals this OR this in Javascript

I am looking at a more elegant way to match and either or in JavaScript.
With strings, we can do the following:
"test".match(/test|otherstring/)
But the number object has no method match. We can of course add this, but my application will be dropped into a large international site with hundreds of separate applications, so this would be a dangerous move.
At this point I have two options:
String(myNumber).match(/test|numbers/)
Or:
if(number === test1 || number === test2)
But neither of these solutions seem very elegant to me. What I would like is to be able to do:
number === test1||test2;
But the result of this is either true if number===test1 of if not it returns test2. Or use brackets:
number === (test1||test2)
But this only compares the first test and returns the result of that.
Here we can have a little more fun with JavaScript wierdness. Bonus points for anyone who can tell me why the following sequence occurs:
13===(13|13)
# true
13===(12|13)
# true
13===(1|13)
# true
13===(133|13)
# false
13===(13|133)
# false
for this question
13===(13|13)
# true
13===(12|13)
# true
13===(1|13)
# true
13===(133|13)
# false
13===(13|133)
# false
A single pipe is a bit-wise OR.
example
alert(6 | 10); // should show 14
8 4 2 1
-------
0 1 1 0 = 6 (4 + 2)
1 0 1 0 = 10 (8 + 2)
=======
1 1 1 0 = 14 (8 + 4 + 2)

Categories