JavaScript - Make a variable change every second - javascript

Ok, so this is my code:
name: function(gameServer, split) {
// Validation checks
var id = parseInt(split[1]);
if (isNaN(id)) {
console.log("[Console] Please specify a valid player ID!");
return;
}
var name = split.slice(2, split.length).join(' ');
if (typeof name == 'undefined') {
console.log("[Console] Please type a valid name");
return;
}
var premium = "";
if (name.substr(0, 1) == "<") {
// Premium Skin
var n = name.indexOf(">");
if (n != -1) {
premium = '%' + name.substr(1, n - 1);
for (var i in gameServer.skinshortcut) {
if (!gameServer.skinshortcut[i] || !gameServer.skin[i]) {
continue;
}
if (name.substr(1, n - 1) == gameServer.skinshortcut[i]) {
premium = gameServer.skin[i];
break;
}
}
name = name.substr(n + 1);
}
} else if (name.substr(0, 1) == "[") {
// Premium Skin
var n = name.indexOf("]");
if (n != -1) {
premium = ':http://' + name.substr(1, n - 1);
name = name.substr(n + 1);
}
}
and i want to change premium to something like <kraken> and <spy> every second, so that then it changes gameServer.skinshortcut to %kraken and then 1 second later it changes that to %spy... and cycles, How do I do this?

Use setInterval(function, delay in ms)

Try:
Var pre_stat=0;
function tgl_pre()
if (pre_stat=0)
{
pre_stat=1;
//change variable to `kraken`;
}
else
{
pre_stat=0;
//change variable to 'spy';
}
setInterval("tgl_pre()", 1000);
end

Related

making custom validation for password field in react

I am making a custom registration page with only 2 values Email and Password, later I will add confirm password as well, for my password field I have some restrictions and I am using some regex and also some custom made code to make the validation.
this is my validateField:
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
//let passwordValidConfirm = this.state.passwordConfirmValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = (value.length >= 5 && value.length <= 32) && (value.match(/[i,o,l]/) === null) && /^[a-z]+$/.test(value) && this.check4pairs(value) && this.check3InRow(value);
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid,
//passwordValidConfirm: passwordValidConfirm
}, this.validateForm);
}
as you can see for
passwordValid
I have made some methods, this one
check3InRow
doesnt work the way I want it to work, this one makes sure, you have at least 3 letters in your string that are in a row so like "abc" or "bce" or "xyz".
check3InRow(value){
var counter3 = 0;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if((lastC + 1) === value.charCodeAt(i)){
counter3++;
if(counter3 >= 3){
alert(value);
return true;
}
}
else{
counter3 = 0;
}
lastC = value.charCodeAt(i);
}
return false;
}
this doesnt work correctly so it should accept this:
aabcc
as a password but not:
aabbc
You are starting your counter from 0 and looking for greater than equal to 3 which will never be 3 for 3 consecutive characters. Rest everything is fine with your code.
check3InRow(value) {
var counter3 = 1;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
alert(value);
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}
Can we not do a simple version of that function? Like
function check3InRow2(value){
for (var i = 0; i < value.length-2; i++) {
const first = value.charCodeAt(i);
const second = value.charCodeAt(i+1);
const third = value.charCodeAt(i+2);
if(Math.abs(second - first) === 1 && Math.abs(third-second) === 1){
return true;
}
}
return false;
}
I mean complexity wise it is O(N) so maybe we can give this a try
Also adding the your function. When you are AT a char then you should consider counter with 1. Because if another one matches it will be 2 consecutive values.
function check3InRow(value) {
var counter3 = 1;
var lastC = value.charCodeAt(0);
for (var i = 1; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}

Create a MR and MC in a javascript calculator

Idealy, I would like my little project to have the memory functions M-, M+, MR and MC.
I was thinking of separate functions and variables to hold the M- and M+.
Is this a normal approach or there is a better one ?
Any idea what might be wrong with my script ? if there is something wrong ?
the number-display ID is the actual calculator screen
the code is :
$(document).ready(function(){
var display = "";
var operators = ["/", "*", "-", "+"];
var decimalAdded = false;
$("button").click(function() {
var key = $(this).text();
//update screen by adding display string to screen with maximum 19 numbers viewable
function updateDisplay() {
if (display.length > 19) {
$("#number-display").html(display.substr(display.length - 19, display.length));
} else {
$("#number-display").html(display.substr(0, 19));
}
}
//clear all entries by resetting display and variables
if (key === "AC" || key === "ON" || key === "MC") {
decimalAdded = false;
display = "";
$("#number-display").html("0");
}
else if (key === "OFF") {
decimalAdded = false;
display = "";
$("#number-display").html("");
}
//clear previous character and reset decimal bool if last character is decimal
else if (key === "CE") {
if (display.substr(display.length - 1, display.length) === ".") {
decimalAdded = false;
}
display = display.substr(0, display.length - 1);
updateDisplay();
}
//add key to display if key is a number
else if (!isNaN(key)) {
display += key;
updateDisplay();
}
//check that . is the first in the number before adding and add 0. or just .
else if (key === ".") {
if (!decimalAdded) {
if(display > 0){
display += key;
}
else {
display += "0" + key;
}
decimalAdded = true;
updateDisplay();
}
}
//if key is basic operator, check that the last input was a number before inputting
else if (operators.indexOf(key) > -1) {
decimalAdded = false;
//first input is a number
if (display.length > 0 && !isNaN(display.substr(display.length - 1, display.length))) {
display += key;
updateDisplay();
}
// allow minus sign as first input
else if (display.length === 0 && key === "-") {
display += key;
updateDisplay();
}
}
// calculate square root of number
else if ( $(this).id === "sqrt") {
var tempStore = display.html();
$("#number-display").html(eval(Math.sqrt(tempStore)));
decimalAdded = false;
}
// change sign of number
else if ($(this).id === "plusmn") {
var newNum = display * -1;
$("#number-display").html(newNum);
}
// create memory plus and minus and calculate MR
else if (key === "M-") {
}
else if (key === "M+") {
}
// percentage function
else if (key === "%"){
}
else if (key == "=") {
//if last input is a decimal or operator, remove from display
if (isNaN(display.substr(display.length - 1, display.length))) {
display = display.substr(0, display.length - 1);
}
var calc = display;
calc = eval(calc);
display = String(calc);
if (display.indexOf('.')) {
decimalAdded = true;
} else {
decimalAdded = false;
}
$("#number-display").html(display);
}
});});
One alternative is a switch statement, which would look something like:
switch (key) {
case "M-":
// do stuff
break;
case "M+":
// do stuff
break;
case "%":
// do stuff
break;
case "=":
// do stuff
break;
}
More documentation on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Nothing happens after Prompt

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});
You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

Javascript(Function to compare objects)

I am trying to create a function which will compare one music album to another but my code does not run. I'd like to know why, because I really cannot see where the problem is and why there is a problem. Thanks very much.
/********* GLOBAL VARIABLES *********/
var BR = "<br />";
var ES = " ";
/********* FUNCTIONS *********/
function compare(album[0], album[1]) {
var sameAlbums = false;
//There has to be an easier way to do all this...
if (album[0].artistName === album[1].artistName && album[0].albumTitle === album[1].albumTitle && album[0].releaseYear === album[1].releaseYear && album[0].ifHQ === album[1].ifHQ && album[0].tracks[0] === album[1].tracks[0] && album[0].tracks[1] === album[1].tracks[1] && album[0].tracks[2] === album[1].tracks[2] && album[0].tracks[3] === album[1].tracks[3] && album[0].tracks[4] === album[1].tracks[4] && album[0].tracks[5] === album[1].tracks[5] && album[0].tracks[6] === album[1].tracks[6] && album[0].tracks[7] === album[1].tracks[7] && album[0].tracks[8] === album[1].tracks[8] && album[0].tracks[9] === album[1].tracks[9] && album[0].tracks[10] === album[1].tracks[10])
{
sameAlbums = true;
}
return sameAlbums;
}
/********* MAIN *********/
function main() {
var alb = new album(2);
for (var i = 0; i < album.length; i++) {
album[i] = {
artistName: "",
albumTitle: "",
releaseYear: 0,
ifHQ: "",
tracks: undefined //tracks here
};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
album[i].ifHQ = prompt("Is the album high quality? Y/N");
while (!(album[i].ifHQ === "Y" || album[i].ifHQ === "N" || album[i].ifHQ === "YES" || album[i].ifHQ === "NO")) {
album[i].ifHQ = prompt("You have entered an invalid response. Is " + album[i].title + " a ifHQ album, Y/N?");
album[i].ifHQ = album[i].ifHQ.toUpperCase();
}
if (album[i].ifHQ === "Y") {
album[i].ifHQ = true;
}
else {
album[i].ifHQ = false;
}
album[i].tracks = new albumay(10);
for (var j = 0 + 1; j < album[i].tracks.length; j++) {
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
for (var key in album[0]) {
document.write(key + ": " + album[0][key] + " ");
document.write(BR);
}
for (var key in album[1]) {
document.write(key + ": " + album[1][key] + " ");
document.write(BR);
}
}
var same = compare(album[0], album[1]);
document.write(same);
// This line calls main, don't change it:
main();
Edited code:
<script type="text/javascript">
/********* GLOBAL VARIABLES *********/
var BR = "<br />";
var ES = " ";
var album = [];
/********* FUNCTIONS *********/
function compare(album1, album2)
{
for (var i in album1)
{
if (album1[i] !== album2[i]) return false;
}
return true;
}
/********* MAIN *********/
function main()
{
var album = [];
var numAlbums = 3;
for (var i = 0; i < numAlbums; i++) {
album[i] = {
artistName: "",
albumTitle: "",
releaseYear: 0,
ifHQ: "",
tracks: undefined //tracks here
};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
album[i].ifHQ = prompt("Is the album high quality? Y/N");
while (!(album[i].ifHQ === "Y" || album[i].ifHQ === "N" || album[i].ifHQ === "YES" || album[i].ifHQ === "NO"))
{
album[i].ifHQ = prompt("You have entered an invalid response. Is " + album[i].title + " a ifHQ album, Y/N?");
album[i].ifHQ = album[i].ifHQ.toUpperCase();
}
if (album[i].ifHQ === "Y")
{
album[i].ifHQ = true;
}
else
{
album[i].ifHQ = false;
}
album[i].tracks = new album(10);
for (var j = 0 + 1; j < album[i].tracks.length; j++)
{
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
for (var key in album[1])
{
document.write(key + ": " + album[1][key] + " ");
document.write(BR);
}
for (var key in album[2])
{
document.write(key + ": " + album[2][key] + " ");
document.write(BR);
}
}
var same = compare(album1, album2);
document.write(same);
// This line calls main, don't change it:
main();
</script>
If you run a debugger on your code, you will see that the problem is in the compare function. In particular, argument names cannot contain square brackets.
I would recommend changing your compare function thus:
function compare (album1, album2) {
for (var i in album1) {
if (album1[i] !== album2[i]) return false;
}
return true;
}
Based on your update
Ok there are still plenty of issues with this code.
First and most important, album1 and album2 are not defined before being compared, for 2 reasons.
Main() is not executed until after they run, so album[] has not been defined
album[1] is not the same as album 1
Some more things to think about:
Array indices start at 0 in javascript. Skipping the first index to get your arrays to start at 1 is considered bad practice.
Instead of the 24 prompts you're doing right now, you should probably consider forms for input. 24 prompts in a row will be very annoying for a user.
You probably want a modal window for your HQ verification. Something like this
An attempt at cleaning up the code
I think you should probably rethink some of the choices here, but here's a cleaned up version of the code that at the very least runs:
jsfiddle
<script type="text/javascript">
/********* FUNCTIONS *********/
function compare(album1, album2)
{
for (var i in album1)
{
if (album1[i] !== album2[i]) return false;
}
return true;
}
/********* MAIN *********/
function main()
{
var album = [];
var numAlbums = 2;
for (var i = 0; i < numAlbums; i++) {
album[i] = {};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
var hq = prompt("Is the album high quality? Y/N")
if(!hq)
{
hq = "";
}
while (true)
{
hq = hq.toUpperCase();
if( hq==="Y" || hq === "YES" )
{
album[i].ifHQ = true;
break;
}
else if( hq ==="N" || hq === "NO" )
{
album[i].ifHQ = false;
break;
}
else
{
hq = prompt(
"You have entered an invalid response. Is " +
album[i].title + " a ifHQ album, Y/N?");
}
}
album[i].tracks = [];
for (var j = 0; j < 10; j++)
{
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
var same = compare(album[0], album[1]);
document.write(same);
}
// This line calls main, don't change it:
main();
</script>

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources