What will run faster? - javascript

I made this thumbnail rotator in javascript, and figured it could be written shorter as seen in the first example, however will this help performance? and are there any general guidelines you should follow in order to maximize javascript speed? (pardon my ugly code, I'm very new to the game)
function mouseOverfirst(videoId){
var num = 8;
var numb = 7;
$('#'+videoId).attr('src',videoId+'/thumb'+numb+'.png');
if(numb == 7){
interval = setInterval(function(){
$('#'+videoId).attr('src',videoId+'/thumb'+num+'.png');
if(num == 15){
num = 1;
}
else
{
num++;
}
},500);
}
}
or this?
function mouseOverfirst(videoId){
var numb = 7;
$('#'+videoId).attr('src',videoId+'/thumb'+numb+'.png');
if(numb == 7){
mouseOver('video1');
}
}
function mouseOver(videoId){
var num = 8;
interval = setInterval(function(){
$('#'+videoId).attr('src',videoId+'/thumb'+num+'.png');
if(num == 15){
num = 1;
}
else
{
num++;
}
},500);
}

The complexity of both programs are the same.
It doesn't matter which one you use, but the 2nd one is more approachable as a function mouseOverFirst and mouseOver can be reused easily.

Related

Determining prime numbers

I'm trying to write a function that determines whether a value is a prime number and then displays a message to provide the outcome. Unfortunately, it doesn't work - no error messages displayed, and I can't see a logical reason why. ( For info, it calls a function numbers() which I have tested independently and it works - it provides a single positive integer). I'm not very experienced in javascript, but have developed the below from learning online. Any pointers in the right direction would be very much appreciated.
function validate() {
var message = "This number is ";
var number;
var value = numbers();
var indicator = true;
for (int i=2; i <= value/2; i++) {
number = value % i;
if (number==0) {
indicator = false;
//or indicator = number % 2 != 0;
break;
}
}
if (indicator) {
message += "a prime number.";
}
else {
message += "not a prime number.";
}
document.getElementById('text').innerHTML = message;
}
Only even number that is prime is 2, so discard all the others that is divisible by 2
Minimize the iteration by considering odds only
Minimize a bit more by iterating to root of given number
So what you can do is write a method like the following:
function isPrime(number) {
if (number === 2) return true;
if (number % 2 === 0) return false;
var flag = true;
var i, length = Math.ceil(Math.sqrt(number));
for (i = 3; i <= length; i += 2) {
if (number % i === 0) {
flag = false;
break;
}
}
return flag;
}
replace int to var in for loop
for (var i=2; i <= value/2; i++) {

Returning factorials in JavaScript

I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)

incorrect variable declaration? or erratic modulo behavior?

why, in the following code, does modB always equal 1? ESPECIALLY considering b % 2 doesn't?
var b = 0;
var modB = 0;
function buttonState() {
b++;
modB = b % 2;
if (modB = 1) {
theButtonState = true;
} else {
theButtonState = false;
}
console.log(b%2);
console.log(modB);
console.log(theButtonState);
}
Change the following line of code:
if (modB = 1)
to
if (modB == 1)
and then try running the program again.
You can do it this way too as (Felix explained):
theButtonState = modB == 1;
Brevity in code improves its readability immensely.

Max call stack exceeded

I understand what maximum call stack exceeded is. However, is there a workaround for this for my code? Furthermore, there will be a time where it eventually will stop looping, that is when position > counter1.
var a = 0;
var b = 1;
var c;
var counter1 = 1;
var position = 0;
window.onload = function() {
var position = prompt("Please enter the position number.","0");
calc1();
}
function calc1() {
if(position <= counter1) {
c = a+b;
counter1++;
calc2();
}
else {
callResult();
}
}
function calc2() {
if(position <= counter1) {
a = b+c;
counter1++;
calc3();
}
else {
callResult();
}
}
function calc3() {
if(position <= counter1) {
b = c+a;
counter1++;
calc1();
}
else {
callResult();
}
}
function callResult() {
if (position %3 == 1) {
document.getElementById("answer").innerHTML = a;
}
else if (position %3 == 2) {
document.getElementById("answer").innerHTML = b;
}
else {
document.getElementById("answer").innerHTML = c;
}
}
You should avoid recursion and use loop. Something like this:
window.onload = function() {
var position = prompt("Please enter the position number.","0");
maincalc();
}
function maincalc() {
var subcalc = [ calc1, calc2, calc3 ];
var calccount = 0;
while(position <= counter1) {
subcalc[ calccounter ]();
calccounter = (calccounter +1) % 3;
}
}
The value of position is given once and never changed.
You then check, if(position <= counter1) in each call calc1, calc2, calc3 which call each other thus:
calc1 -> calc2 -> calc3 -> calc1 -> ...
This will clearly continue until you run out of stack space.
Perhaps if you increment position instead of counter1 or keep calling while position is greater than the counter this problem will go away,
i.e.
if(position > counter1)
You probably need to step back and think about what you are really trying to do.
as I understand you are calculating Fibonacci numbers sum?
see this Javascript Fibonacci answer to learn how to do it much easier and without any recursive calls

Javascript prime number error?

Could someone please help me find the error in this code? I'm reading through what I came up with and it logically makes sense to me each step of the way, but it's not producing the desired result. At the end I test calling the function with 6.
function is_prime(num) {
if (isNaN(num)) return false;
var numFactors = 0;
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
if (numFactors === 2) {
return true;
}
else {
return false;
}
}
console.log(is_prime(6));
You are returning the function from inside the forloop.
So it never hits the other statements
Check Fiddle
I believe the problem you are having is that you are potentially returning your numFactors too early:
for (i=1; i<=num; i++) {
if (num % i === 0) {
numFactors += 1;
}
return numFactors;
}
Here, you are returning the numFactors at the end of your first loop, so it never actually finishes the full test.
Counting factors is not a right approach -
use this -
function is_prime(num) {
if (isNaN(num)) return false;
var k = Math.sqrt(num);
for (i=2; i<=k; i++) {
if(num%i===0)return false;
}
return false;
}
console.log(is_prime(6));
As you are stepping through all numbers from 1 to num for factrorization you might as well pick them up as factors and get a bit more out of your function:
function fact(num) {
if (isNaN(num)) return false;
var Factors=[];
for (i=1; i<=num; i++) {
if (num % i == 0) Factors.push(i)
}
return Factors
}
console.log('factors: '+fact(27));
console.log('is prime: '+fact(27).length===2);

Categories

Resources