push name and amount to javascript object - javascript

I am trying to create an app for a site and users can send money to people on this site. Kinda like twitch. So i wanna create a toplist but i am new to using objects so i'm having some trouble and to explain my problem in a more easy way i added comments in my code
var myvar = [];
cb.onTip(function(tip){
// If username already exists in myvar then i want to just increase the amount for this user else if username does not exist i want to push up the name and amount to myvar
myvar.push({name: tip.from_user, amount: tip.amount});
});
function sendtoplist(user) {
var msg;
for(var i = 0; i <= 3; i++) {
// Here i am trying to create a toplist but i want to sort it by the amount. How can i do this?
msg += myvar.name + ' ' + myvar.amount+'\n';
}
// For some reason this sendNotice returns undefined (probably because i have no idea how to work with objects)
cb.sendNotice(msg, '', '#000000', '#FFFFFF', 'bold');
cb.setTimeout(sendtoplist, 30000);
}
cb.setTimeout(sendtoplist, 30000);

Do you know which specific function is not working?
If so, which error does it show to you?
to your first function:
//myvar should be already as an array, imported from a database for example
cb.onTip(function(tip){
// If username already exists in myvar then i want to just increase the amount for this user else if username does not exist i want to push up the name and amount to myvar
var personName = {};
personName.name = tip.from_user;
personName.amount = tip.amount;
var userExist = false;
for (let i=0; i < myvar.length; i++) {
if (myvar[i].name == personName.name){
myvar[i].amount += personName.amount;
userExist = true;
break;
}
}
if (!userExist) {
myvar.push(personName);
}
});
Is it clear for you? if not let me know.
To your 2nd function, learn some AngularJS basics, it is pretty easy, there you can use a filter and exactly the filter you need which is called ("orderBy")
Note:
I really recommend you to learn a framework, instead of using plain JS. If you dont want to learn that much, just learn AngularJS, it must be easy to learn. But if you think you would like to learn some modern framework, the learn Angular (working with typescript is needed)

Related

cart challenge javascript logic. is there more than one way to solve?

I just finished the JS intro with code academy, so im kinda new to this.
Please look at the following 2 pieces of code, of a Shopping Cart Challenge.
The first one is the correct code that I found online, in which It scans an array that is already defined and then when inputting a piece of information (in this case "item") an output of another piece of information ("price") is received.
Here is the "right" solution:
// Declare Array
var shoppingCart = [];
// Declare function addToCart
addToCart = function(name,price) {
this.name = name;
this.price = price;
shoppingCart.push(this.name,this.price);
};
function priceCheck(itemName) {
var i = 0;
for(i; i <= shoppingCart.length; i++) {
if(itemName === shoppingCart[i]) {
console.log(shoppingCart[i += 1]);
break;
}
else {console.log("the searched item is not in the shopping cart");}
}
}
as you can see, this person used .this.
In my code i just added an object (like was instructed).
Is my logic completely off, or i just need to do some repairs?
My code:
shoppingCart = [];
function addToCart(itemName, itemPrice){
const shiny = {
name: itemName,
price: itemPrice
};
shoppingCart.push(shiny);
console.log(shoppingCart);
}
function priceCheck(itemName){
for(i=0;i<=shoppingCart.length; i++){
if(itemName===shoppingCart[i]){
return itemPrice;
} else{
console.log('item isnt in cart');
}}}
addToCart('apple',20);
console.log(shoppingCart);
priceCheck('apple');
It works fine until it reaches the priceCheck('apple'); - then it seemes i cannot find 'apple' in the array.
I try to understand if I need to use the (.this) and if I can do it the way I wrote.
PS - sorry if its a mess, its a bit hard for me to explain what im trying to understand :)
PSS - Im not just looking to solve the challenge but really develop a "coding mindset for problems".
THX!
The "right" solution? Rather not.
addToCart = function(name,price) {
This is an undeclared and unneccessary function expression. One should rather do:
function addOne(name, price){
And accessing this here is not really a good practice cause its missleading. I would always only use this if you are just refering to OOP code. Additionally the following makes no sense to me:
shoppingCart.push(this.name,this.price);
cause that adds the name and the price as different array elements. And this sets variables that are never used (why??):
this.name = name;
this.price = price;
So your solution is actually better than the "right" one IMO. However there are a few things:
for(i=0;i<=shoppingCart.length; i++){
This iterates until i is equal to the length, but as arrays are zero based there is no element at that position. Do:
for(let i = 0; i < shoppingCart.length; i++)
Additionally, objects are compared by reference, but you actually want to compare them by value. E.g. you could take the name property:
if(name === shoppingCart[i].name)
And a small style tip, dont do this:
}}}
How i would do that:
const cart = [];
function addToCart(name, price){
cart.push({name, price});
}
function priceOf(findName){
for(const {name, price} of cart)
if(findName === name) return price;
return NaN;
}
shoppingCart[i] is an object and name and price are its properties.
You need to access the properties of the object instead.
replace itemName == shoppingCart[i] with itemName == shoppingCart[i].name and then you can get the price with shoppingCart[i].price
shoppingCart = [];
function addToCart(itemName, itemPrice){
const shiny = {
name: itemName,
price: itemPrice
};
shoppingCart.push(shiny);
console.log(shoppingCart);
}
function priceCheck(itemName){
for(i=0;i<=shoppingCart.length; i++){
if(itemName===shoppingCart[i].name){//here
return shoppingCart[i].price;//here
} else{
console.log('item isnt in cart');
}}}
addToCart('apple',20);
console.log(shoppingCart);
console.log(priceCheck('apple'));
An obvious issue is here:
if(itemName===shoppingCart[i]){
You're comparing itemName to the object containing name and price instead of the name.
I don't remember the exact JS syntax for this but it should be something like
if (itemName === shoppingCart[i].name) {

Can you access javascript custom class objects inside an array and how?

Im working on a RPG-game project made in plain javascript just for fun, but can't seem to understand how javascript build-in classes work since they behave quite a lot differently than I am used to in Java or C#. So here is the problem:
If I have made custom class something along the lines like this:
Class Player_animation{
constructor(animationX,animationY,animation_state,xPos,yPos,destX,destY){
this.animationX = animationX;
.
. (the basic setup for all the attributes as the first one);
.
set animationX(value){
this._animationX = value;
}
//all the setters as that one
update(){
if(this._animationX===480 && this._animation_state==='idle')
this._animationX=0;
else if(this._animationX===720 && this._animation_state !== 'attack'){
this._animationX=0;
}
else if(this._animationX===840){
this._animationX=0;
this._animationY = 0;
this._animation_state = 'idle';
}
if(this._xPos!== this._destX || this._yPos!== this._destY){
if(this._xPos<this._destX){
this._animation_state = 'facing_right';
this._animationY = 240;
}
if(this._xPos>this._destX){
this._animation_state = 'facing_left';
this._animationY = 360;
}
}
else{
if(this._animation_state === 'facing_right')
this._animationY = 0;
if(this._animation_state === 'facing_left')
this._animationY = 120;
if(this._animation_state!=='attack'){
this._animation_state = 'idle';
}
}
}
}
And i can call an new made class object no problem in my program like this:
var player_animation = new Player_animation(0,0,'idle',0,0,0,0);
player_animation.update();
Can I somehow make an array of these custom classes that I call with that function. I have tried two of the following approaches like this:
var array = [];
array.push[player_animation,player_animation2];
for(var unit in array){
unit.update();
}
Second approach i tried that does not work:
var array = [];
array.push[player_animation,player_animation2];
for(var i = 0; i < array.Lenght; i++){
array[i].update();
}
Working code goes through this loop (I know that I should limit the fps here):
function frame(){
update();
requestAnimationFrame(frame);
}
function update(){
player_animation.update();
enemy_animation.update();
}
requestAnimationFrame(frame);
Is something like this even possible in plain javascript?
My game loop and update work fine with all of the objects defined called separately but that will be a hassle after there will be 10+ objects in game.
In Java i was able to store all of the game_objects in an array where their functions would be called through a for loop so finding it hard to understand why it does not work as that in javascript.
You have many problems, none of them relating to how classes work in JavaScript.
array.push[player_animation,player_animation2];
push is a function. You call it with () not [].
for(var unit in array){
in loops over the property names in an object. Avoid using it for arrays. If you do use it, then you would need array[unit] to get the value and not simply unit.
for(var i = 0; i < array.Lenght; i++){
JavaScript is case-sensitive
JavaScript requires that property names be spelt correctly
It is length not Lenght.

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

Getting the length of a textbox value or content using JavaScript

This is something that's driving me nuts:
I have this code and it works: I am trying to learn JavaScript before becoming addicted to JQuery. My sample project involves getting the value of the text-box, and validating according to it's length. the name of the form is membership.
Example: This works:
function validateForm()
{
var element = document.membership;
if(element.txtName.value == "")
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
But this doesn't:
function validateForm()
{
var element = document.membership;
var nameLenght = element.txtName.value.lenght;
if(nameLenght < 1)
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
Just an FYI: I am new to JavaScript but very familiar with the syntax. I just want to learn the basics and move up.
I even read some solutions on here but feel I am simply sinking deeper.
Thanks for your help.
May be it is just because of typo in length here:
element.txtName.value.lenght;
must be element.txtName.value.length;.
If you want it to run every time user presses key , then look here: How to check string length with JavaScript
you can use this function as well
var a = txtName.value;
if (a.length < 1) {
alert('your message');
return false;
}

Avoiding having to write the same word over and over again

I'm very new to javascript so this question might sound stupid. But what is the correct syntax of replacing certain words inside variables and functions. For example, I have this function:
function posTelegram(p){
var data = telegramData;
$("#hotspotTelegram").css("left", xposTelegram[p] +"px");
if (p < data[0] || p > data[1]) {
$("#hotspotTelegram").hide()
} else {
$("#hotspotTelegram").show()
}
};
There is the word "telegram" repeating a lot and every time I make a new hotspot I'm manually inserting the word to replace "telegram" in each line. What would be a smarter way of writing that code so that I only need to write "telegram" once?
Group similar / related data in to data structures instead of having a variable for each bit.
Cache results of calling jQuery
Use an argument
function posGeneral(p, word){
// Don't have a variable for each of these, make them properties of an object
var data = generalDataThing[word].data;
// Don't search the DOM for the same thing over and over, use a variable
var hotspot = $("#hotspot" + word);
hotspot.css("left", generalDataThing[word].xpos[p] +"px");
if (p < data[0] || p > data[1]) {
hotspot.hide()
} else {
hotspot.show()
}
};
You can't always avoid this kind of repetition (this is general to all programing languages).
Sometimes, you can make generic functions or generic classes, for example a class which would embed all your data :
Thing = function(key, xpos) {
this.$element = $('#hotspot'+key);
this.xpos = xpos;
};
Thing.prototype.pos = function (p, data) {
this.$element.css("left", this.xpos[p] +"px");
if (p < this.data[0] || p > this.data[1]) {
this.$element.hide()
} else {
this.$element.show()
}
};
And we could imagine that this could be called like this :
var telegramThing = new Thing('telegram', xposTelegram);
...
telegramThing.pos(p, data);
But it's really hard to make a more concrete proposition without more information regarding your exact problem.
I recommend you read a little about OOP and javascript, as it may help you make complex programs more clear, simple, and easier to maintain.
For example, using a Thing class here would enable
not defining more than once the "#hotspotTelegram" string in your code
reusing the logic and avoid making the same code with another thing than "telegram"
not having the Thing logic in your main application logic (usually in another Thing.js file)
But don't abstract too much, it would have the opposite effects. And if you don't use objects, try to keep meaningful variable names.
var t = "Telegram";
var $_tg = $('#hotspotTelegram');
$_tg.css("left", "xpos"+t[p] + "px"); // not sure about this line, lol
$_tg.hide();
$_tg.show();
etc.
you can create a selector as variable, something like this
function posTelegram(p){
var data = telegramData;
var $sel = $("#hotspotTelegram");
$sel.css("left", xposTelegram[p] +"px");
if (p < data[0] || p > data[1]) {
$sel.hide()
} else {
$sel.show()
}
};

Categories

Resources