I'm taking a hackerrank test that is a simple puzzle that states that 8=2 and 0,4,6,9 = 1 and all other numbers are equal to 0. So I wrote this function in javascript, and it works in ie out of notepad, but when I put it into the hackerrank console I get an error that points to the .count. Does anyone know why this would happen? I'm new to javascript so it maybe be a simple I just can't figure it out. Any help would be great. Thanks
var str = prompt("Number: ");
String.prototype.count = function(match) {
var res = this.match(new RegExp(match,"g"));
if (res==null) { return 0; }
return res.length;}
document.write((str.count(8)*2)+ str.count(4) + str.count(6) + str.count(9) + str.count(0));
};
Not sure what you mean. Maybe a switch is in order:
function pickANumber(num){
switch(num){
case 8:
return 2;
case 0: case 4: case 6: case 9:
return 1;
default:
return 0;
}
}
console.log(pickANumber(8));
console.log(pickANumber(5));
console.log(pickANumber(9));
It's generally frowned upon to prototype built-in objects like String or Array. It would be much easier to just define a standalone function that did the exact same thing, and you shouldn't have to worry about count not being defined. The problem might be that Hacker Rank isn't letting you modify the String object? Not sure about that though. Try using something like this:
function count(str, letter) {
// your code
}
Related
So I have a bunch of regexes and I try to see if they match with another string using this If statement:
if (samplestring.match(regex1)) {
console.log("regex1");
} else if (samplestring.match(regex2)) {
console.log("regex2");
} else if (samplestring.match(regex3)) {
console.log("regex3");
}
But as soon as I need to use more regexes this gets quite ugly so I want to use a switch case statement like this:
switch(samplestring) {
case samplestring.match(regex1): console.log("regex1");
case samplestring.match(regex2): console.log("regex2");
case samplestring.match(regex3): console.log("regex3");
}
The problem is it doesn't work like I did it in the example above.
Any Ideas on how it could work like that?
You need to use a different check, not with String#match, that returns an array or null which is not usable with strict comparison like in a switch statement.
You may use RegExp#test and check with true:
var regex1 = /a/,
regex2 = /b/,
regex3 = /c/,
samplestring = 'b';
switch (true) {
case regex1.test(samplestring):
console.log("regex1");
break;
case regex2.test(samplestring):
console.log("regex2");
break;
case regex3.test(samplestring):
console.log("regex3");
break;
}
You can use "not null":
switch(samplestring){
case !!samplestring.match(regex1): console.log("regex1");
case !!samplestring.match(regex2): console.log("regex2");
case !!samplestring.match(regex3): console.log("regex3");
}
I have several numbers to proceed, let's assume that my numbers are :
14000,32100,510,2100, and 10000
So, how to make the numbers recognized as thousands or hundreds in javascript?
Is there any function for this?
Use a logarithm. A base 10 log if available, or make a base 10 log from a natural log (ln) via ln(n)/ln(10). Like so:
var log10=function(n){return Math.log(n)/Math.log(10);};
log10(100); //2
log10(10000); //4
log10(1000000);//6, uh actually 5.999999999999999
Might need to round the result due to lack of precision. Rounded version:
function log10(n){
return Math.round(100*Math.log(n)/Math.log(10))/100;
}
[10,100,1000,10000,100000,1000000].map(log10);
/*
1,2,3,4,5,6
*/
Also you should cache the Math.log(10) result if performance is an issue;
Try this one:
var number = 5300;
function NumberName(number)
{
switch (number.toString().length)
{
case 3:
return "hundreds";
case 4:
return "thousands";
}
}
int x = Math.floor(Math.log10(number)) + 1;
returns the total number of digits of a number (for 100 returns 3, for 1000 returns 4)
I don't know if there is a built-in function like that sorry, but if you just have integers you can write your own function for that:
function numberDigits(number) {
return number.toString().length
}
Now you can easily dicide if the number is thousands or hundreds etc...
Note that this only works with integer values!
I don't know how your Mark-up looks like :
But for a given markup like below:
<div class="save-sale" style="font-size: .8em; padding-top: 4em">10000</div>
You can use something like:
$(function () {
$(".save-sale").click(function (i) {
var a = $.trim($(".save-sale").text()).length;
alert(a);
});
});
FIDDLE
In JavaScript, No method exist to identify a number is hundreds or thousands, but you can create your own
ex:
function check(num){
if(num>999) { return 'thousands'; }
if(num>99) { return 'hundreds'; }
}
I have an array with the following value:
2, *, 5
How can I execute this string like so:
2 * 5
so the result returned is 10?
The most horribly insecure way possible would be to do something like this:
eval([2,"*",5].join(''))
But I could never recommend doing that, like ever. The "right" way to do it would be to write some kind of parser.
var ops = [2,"*",5]
var val = ops.shift();
while(ops.length > 0) {
var item = ops.shift();
switch(item) {
case "*": val *= ops.shift();
case "+": val += ops.shift();
case "-": val -= ops.shift();
case "/": val /= ops.shift();
}
}
This would essentially work like a very simple calculator... but I still couldn't really recommend this approach.
What are you trying to do exactly? Maybe there is a better way to model what you are trying to do other than an array?
Assuming you can handle your own precedence using order and parentheses, and you are okay with using eval, then use eval:
var str = "2,*,5";
var exp = str.split(",").join("");
var n = eval(exp);
alert(n);
Also, that assumes that you have no spaces in your initial string.
You could just do:
var array = [2, '*', 5];
eval(array.join(''));
This is one of the few things eval is useful for, however you likely don't want to give it just anything.
I have some simple variables whose values are numeric strings:
var s = '10*10*10',
v = '60*10';
I want to turn s into 1000 and v to 600.
Use eval() function:
var result = eval('10*10*10');
alert(result); // alerts 1000
If the strings are from a truly trusted source, you can use eval to do that:
var s = '10*10*10';
var result = eval(s);
But note that eval fires up a JavaScript parser, parses the given string, and executes it. If there's any chance that the given string may not be from a trusted source, you don't want to use it, as you're giving the source the ability to arbitrarily execute code.
If you can't trust the source, then you'll have to parse the string yourself. Your specific examples are easy, but I'm sure your actual need is more complex.
The dead easy bit:
var s, operands, result, index;
s = '10*10*10';
operands = s.split('*');
result = parseInt(operands[0], 10);
for (index = 1; index < operands.length; ++index) {
result *= parseInt(operands[index], 10);
}
...but again, I'm sure your actual requirement is more complex — other operators, spaces around the values, parentheses, etc.
Picking up on Andy E's comment below, whitelisting might well be a way to go:
function doTheMath(s) {
if (!/^[0-9.+\-*\/%() ]+$/.test(s)) {
throw "Invalid input";
}
return eval('(' + s + ')');
}
var result = doTheMath('10*10*10'); // 1000
var result2 = doTheMath('myEvilFunctionCall();'); // Throws exception
Live example
That regexp may not be perfect, I'd stare at it long and hard before I'd let any unwashed input head its way...
this could be achieved quite simply without resorting to eval
function calc(s) {
s = s.replace(/(\d+)([*/])(\d+)/g, function() {
switch(arguments[2]) {
case '*': return arguments[1] * arguments[3];
case '/': return arguments[1] / arguments[3];
}
})
s = s.replace(/(\d+)([+-])(\d+)/g, function() {
switch(arguments[2]) {
case '+': return parseInt(arguments[1]) + parseInt(arguments[3]);
case '-': return arguments[1] - arguments[3];
}
})
return parseInt(s);
}
alert(calc("10+5*4"))
You can use the eval function to evaluate an expression in a string:
var evaluated = eval(s);
alert(evaluated) will then alert 1000.
If you "just" want to have these numbers out of the string you can do
eval(s)
to get "10*10*10" as a Number
So lets say I had this switch:
switch(str){
case "something": //a defined value
// ...
break;
case /#[a-zA-Z]{1,}/ //Matches "#" followed by a letter
}
I'm almost sure that the above is almost impossible...but what would be the best way to achieve something similar? Maybe just plain if..else..ifs? That'd be boring...
So how would you achieve this?
You can get the matches for various patterns before you begin the switch,
and set the cases to the index of the match.
(Other conditionals would be easier to read, if not more efficient.)
//var str= 'something';
var str='#somethingelse';
var M= /^(something)|(#[a-zA-Z]+)$/.exec(str);
if(M){
switch(M[0]){
case M[1]:
// ...
alert(M[1]);
break;
case M[2]:
//...
alert(M[2])
break;
}
}
You can use a single regexp. It is not necessarily less boring but it gets the job done.
var result = /(something)|(#[a-zA-Z]{1,})/.exec(str);
if (!result) {
// Handle error?
} else if (result[1]) {
// something
} else if (result[2]) {
// #[a-zA-Z]{1,}
}