Javascript(Function to compare objects) - javascript

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>

Related

Discord.js Bot getting offline without any errors

i've created bot for analyze PUBG stats and set up specific role based on stats.
Last time i added check for casual mode, bot is checking last 25games of player and check if there were more than 85% bots. On small group of players it worked good but know i'm caching up around 200players and bot just going offline without any errors. Im using premium account on replit.com to keep him 24h up, stoping and starting again fixes the problem till next loop. Im not running out the session limits from disocrd
Discord.js debug don't show errors.
image
Dicord_Bot.on("debug", (e) => console.log(e))
exports.run = async (bot, message, args) => {
var membersArray = message.guild.members.cache;
const insertInto = bot.dbsql2.prepare('INSERT INTO testo(nickname, pubg_id, match_id , assists, damageDealt, headshotKills, kills, win) VALUES (?,?,?,?,?,?,?,?)');
for (let [snowflake, guildMember] of membersArray) {
if (guildMember.user.bot) {
continue;
}
var nickname = guildMember.nickname;
if (!nickname)
nickname = guildMember.user.username;
console.log("Sprawdzam " + nickname);
var matchesList = bot.pubgAPI.getPlayerMatchesList(bot, nickname);
var pubgID = bot.pubgAPI.getPlayerID(bot, nickname);
if(pubgID === 0 || pubgID === -1) {
continue;
}
for (let i = 0; i <= 25; i++) {
var participants = 0;
var bots = 0;
var players = 0;
var lastStats = [0, 0, 0, 0, 0, 0, 0];
if (matchesList[i] === undefined) {
console.log("Brak meczu");
continue;
}
var matchStats = bot.pubgAPI.getMatchStats(bot, matchesList[i].id)
if (matchStats === undefined) {
console.log("Brak stat");
continue;
}
if (matchStats.data === undefined) {
console.log("Brak daty");
continue;
}
if (matchStats.data.attributes === undefined) {
console.log("Brak atrybutow");
continue;
}
if (matchStats.data.attributes.stats === undefined) {
console.log("Brak statow");
continue;
}
if (matchStats.data.attributes.gameMode === "squad" && matchStats.data.attributes.matchType === "official") {
for (let j = 0; j < matchStats.included.length; j++) {
if (matchStats.included[j] === undefined) {
continue;
}
if (matchStats.included[j].attributes === undefined) {
continue;
}
if (matchStats.included[j].attributes.stats === undefined) {
continue;
}
if (matchStats.included[j].type === "participant") {
participants++;
if (matchStats.included[j].attributes.stats.playerId.includes("ai.")) {
bots++;
}
else {
players++;
}
}
if (matchStats.included[j].attributes.stats.playerId === pubgID) {
lastStats[0] += matchStats.included[j].attributes.stats.assists
lastStats[1] += matchStats.included[j].attributes.stats.damageDealt
lastStats[2] += matchStats.included[j].attributes.stats.headshotKills
lastStats[3] += matchStats.included[j].attributes.stats.kills
if (matchStats.included[j].attributes.stats.winPlace === 1) {
lastStats[6] += 1
}
else {
lastStats[4] += 1
}
lastStats[5] += 1
}
}
if (((bots / participants) >= 0.50)){
var returnMessage = "**" + nickname + "**" + " miał " + ((bots / participants) * 100).toFixed(2) + "% botów.";
returnMessage += "\n**Usuwamy ze statystyk:**";
returnMessage += "\nDamage:" + lastStats[1].toFixed(2)
returnMessage += "\nAsysty:" + lastStats[0]
returnMessage += "\nHeadshoty:" + lastStats[2]
returnMessage += "\nKille:" + lastStats[3]
if (lastStats[6] != 0) {
returnMessage += "\nWin:1"
}
bot.channels.cache.get("952186890499530792").send(returnMessage);
insertInto.run(nickname,pubgID,matchesList[i].id,lastStats[0],lastStats[1],lastStats[2],lastStats[3],lastStats[6])
}
}
var sleep1 = await bot.sleepFor(10);
}
var sleep = await bot.sleepFor(1000)
}
}
exports.help = {
name: "test",
channel: "952186890499530792",
members: ["248165905119313948"]
}

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

How to delete object in array using localstorage?

I have to delete object in array and it should be deleted from localstorage. I am trying to delete it by using splice method but not actually getting how to use it.
Folloeing is my code which i have tried-
var details = [];
function addEntry() {
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
var srno = document.getElementById("txtpid").value;
var name = document.getElementById("txtpname").value;
var dob = document.getElementById("txtpdob").value;
var email = document.getElementById("txtpemail").value;
var address = document.getElementById("txtpaddr").value;
var contact = document.getElementById("txtpmobile").value;
var obbbj = {
txtpid: srno,
txtpname: name,
txtpdob: dob,
txtpemail: email,
txtpaddr: address,
txtpmobile: contact
};
localStorage.setItem("details", JSON.stringify(obbbj));
existingEntries.push(obbbj);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
showEntry();
console.log(existingEntries);
//location.reload();
}
function showEntry() {
var messageBox = document.getElementById("display");
messageBox.value = "";
document.getElementById("txtpid").value = "";
document.getElementById("txtpname").value = "";
document.getElementById("txtpdob").value = "";
document.getElementById("txtpemail").value = "";
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpmobile").value = "";
var render = "<table border='1'>";
render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";
var allEntriesoo = {};
var detailsOOO = {};
for (i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var person = localStorage.getItem(key);
if (key == 'allEntries')
allEntriesoo = JSON.parse(person);
if (key == 'details')
detailsOOO = JSON.parse(person);
var data = JSON.parse(person);
}
for (var key in allEntriesoo) {
console.error(allEntriesoo[key])
render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";
}
render += "</table>";
display.innerHTML = render;
}
function nameVal() {
document.getElementById("txtpname").focus();
var n = document.getElementById("txtpname").value;
var r;
var letters = /^[a-zA-Z]+$/;
if (n == null || n == "") {
alert("please enter user name");
return null;
n.focus();
} else {
if (n.match(letters) && n != "") {
r = ValidateEmail();
return r;
} else {
alert("please enter alphabates");
document.getElementById("txtpname").value = "";
document.getElementById("txtpname").focus();
return null;
}
}
}
function ValidateEmail() {
var uemail = document.getElementById("txtpemail").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
document.getElementById("txtpemail").value = "";
document.getElementById("txtpemail").focus();
return null;
}
}
function alphanumeric() {
var uadd = document.getElementById("txtpaddr").value;
var letters = /^[0-9a-zA-Z]+$/;
if (uadd == null || uadd == "") {
alert("plz enter address");
uadd.focus();
} else {
if (uadd.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpaddr").focus();
return false;
}
}
}
function cntVal() {
var n = document.getElementById("txtpmobile").value;
var r1;
var letters = /^\d{10}$/;
if (n !== null || n !== "") {
if (n.match(letters)) {
r1 = alphanumeric();
return r1;
} else {
alert("please enter contact number");
document.getElementById("txtpmobile").value = "";
document.getElementById("txtpmobile").focus();
return null;
}
} else {
alert("please enter contact Number");
return null;
n.focus();
}
}
function deleteEntry(id) {
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index = i;
break;
}
}
if (index === undefined) return
entry.splice(index, 1);
localStorage.setItem('entry', JSON.stringify(entry));
}
function clearstorage() {
localStorage.clear();
window.location.reload();
}
window.onload = function() {
showEntry();
};
In your deleteEntry function you are setting a new item in localStorage called 'entry'. So you are not setting 'allEntries' and thats probably why its showing up like that, 'allEntries' has not been updated. So just set all entries again. localStorage.setItem('allEntries', JSON.stringify(entry));
You are also missing the '?' for you variable 'entry'...
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- it should look like this.
Its the same as an 'if else statement'
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index=i;
break;
}
}
if(index === undefined) return
entry.splice(index, 1);
localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this
}
You can use create a temporary object and then replace it in localStorage.
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = JSON.parse(localStorage.getItem('allEntries'));
var temp= [];
for (var i = 0; i < entry.length; i++) {
if (entry[i].id !== id) {
temp.push(entry[i]);
}
}
localStorage.setItem('entry', JSON.stringify(temp));
}

JavaScript - Make a variable change every second

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

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Categories

Resources