Adding data objects integers to localstorage - javascript

I want to add data objects returned from the server and store them in local storage.
data.Total is a set of integer numbers that come from the server on successful requests.
I somehow need to add them before storing them in local storage
let score = data.Total+localStorage.getItem("RelationScore");
let removeNull = score.replace('null', '');
localStorage.setItem("RelationScore", removeNull );
Example Output: 1234
I want to add those and store them to a single variable, so the result based on the example should be 10

All items are saved into localStorage as string, So you will need to parse them first:
let score = localStorage.getItem("RelationScore");
score = score === null ? 0 : parseInt(score);
localStorage.setItem("RelationScore", data.Total + score);
I assume that data.Total is an integer like you said. If it is not, then you'll have to parse it too.
If you want to only update the total when the item is not zero:
let score = localStorage.getItem("RelationScore");
if(score !== null) {
score = parseInt(score);
if(score !==0)
localStorage.setItem("RelationScore", data.Total + score);
}

Based on your comments, you're probably looking for this code :
let stored = (localStorage.getItem("RelationScore") === null ? 0 : parseInt(localStorage.getItem("RelationScore")));
let score = parseInt(data.Total) + stored;
localStorage.setItem("RelationScore", score);

Even if you put an Integer into localStorage, it's going to be saved as a String.
If you add a number to a String in JavaScript, you are just appending the number to the String, "10" + 1234 === "101234";. So you will need to parse the String to a number:
let score = 0;
if (localStorage.getItem("RelationScore")) { // if the Item exists
score += parseInt(localStorage.getItem("RelationScore")); // make a number out of it and add it to the score
}
score += parseInt(data.Total); // add data.Total, even if the Item hasn't already been set
localStorage.setItem("RelationScore", score); // finally save the score to localStorage

Related

I'm trying to use a while loop to take user input and insert into an array Javascript

So im trying to take userResponse from prompt, convert it into an integer, then take that response and add it to my total. As long as my total is under 35 it should keep looping. Once the total userResponse has reached 35, the userResponse should be pushed into shoppingCart array and then the loop should break and an alert appear that they have reached the threshhold of 35. (btw sorry I'm new to stackoverflow, excuse my newbieness).
//==== VARIABLES ========
let shoppingCart = [];
let shippingThreshhold = 35;
let userResponse;
let total;
//==== LOGIC ========
//CHECK FOR ITEMS UNTIL THRESHOLD IS MET.
while (total < shippingThreshhold){
//GET ITEM COST FROM USER
let userResponse = prompt("What is the value of the item you have selected?");
//CONVERT USER INPUT TO A NUMBER
userResponse.parseInt();
//ADD ITEM COST TO RUNNING TOTAL VARIABLE
let total = shippingThreshhold - userResponse
//PUSH ITEM COST TO CART ARRAY
userResponse.concat(shoppingCart);
}
//SEND POPUP MESSAGE TO USER
alert("Your shipping for this order will be free!");
There are a few issues with your code:
You need to initialize total
You don't add item cost to total properly
You don't parse the userResponse using parseInt properly
You don't push userResponse to the shoppingCart properly
There's no reason to declare userResponse globally.
Some improvements you could also make:
No need to store the total, as you can use the shoppingCart to calculate that (but I've kept total to keep it simpler).
Show the user their cart both as they go and at the end.
Format the shippingThreshold constant using a conventional naming format for constants (all caps separated by underscore).
Use const instead of let when possible, to avoid unintentionally overwriting variable values.
Handle edge cases.
//==== VARIABLES ========
const shoppingCart = [];
const SHIPPING_THRESHOLD = 35;
let total = 0;
//==== LOGIC ========
//CHECK FOR ITEMS UNTIL THRESHOLD IS MET.
while (total < SHIPPING_THRESHOLD) {
//GET ITEM COST FROM USER
const userResponse = prompt(`Your cart: ${shoppingCart.length ? shoppingCart : 'empty' }. What is the value of the item you have selected?`);
if (userResponse === null) {
break
} else {
//CONVERT USER INPUT TO A NUMBER
const itemCost = parseInt(userResponse);
if (Number.isNaN(itemCost)) {
alert(`"${userResponse}" is not a number please try again or press cancel to exit.`)
} else {
// ADD TO TOTAL
total += itemCost
//PUSH ITEM COST TO CART ARRAY
shoppingCart.push(itemCost);
}
}
}
//SEND POPUP MESSAGE TO USER
if (total >= SHIPPING_THRESHOLD) {
alert(`Your shipping for this order will be free! Your cart: ${shoppingCart}`);
} else {
alert("Thanks for visiting!")
}

Can't get stable result with copying random values from array to an object

So I'm in process of creating a bot for a tournament and I got stuck on the part where I want to split players in pairs for play-off-style tournament. I just want to take 2 random players, get them from an array and write it as a value to a key as a round id for an object. Also I should not use those players again in the pair, so need to delete them or smth.
Here's the code:
var users = inc.funcs.getDatabase() //Getting a raw array of users (using my func that's basically a simplified fs.readFileSync func)
var tournamentPairs = new Object() //Object initialization
var id = 1
for (var i = 0; i < 16; i = i + 2) {
var first = Math.floor(Math.random() * (users.length + 1)) //Randomizing 2 indexes
var second = Math.floor(Math.random() * (users.length + 1))
var player1 = client.users.get(users[first]) //Getting the players by id
var player2 = client.users.get(users[second])
tournamentPairs[id++] = [player1.id, player2.id] //Writing to the object
users.splice(first, 1) //Deleting user's indexes from the array to not use them anymore.
users.splice(second, 1)
}
console.log(tournamentPairs)
It works perfectly on the outside, but has a bad habit of duplicating users and I once could have a gamergod98 vs gamergod98 for example. I tried console.log this crap but it often get an error when trying to console.log player2 because it's undefined for some reason. If I try to print users[second] I get undefined though it never happened for the first player. So I tried different ways to prevent situations like this: first == second. Long story short it didn't help much.
I have 9 days 'till tournament starts, any ideas on how to improve this code?
You are getting undefined because you are going out of bounds of your users list. For a list of length the last element is list[length-1], but you are generating random numbers up to length.
To fix duplicate users, remove the first selected user from the list before selecting the second one (or for a less destructive approach, mark already selected users).
var id = 1
for (var i = 0; i < 16; i = i + 2) {
var first = Math.floor(Math.random() * users.length)
var player1 = client.users.get(users[first])
users.splice(first, 1)
var second = Math.floor(Math.random() * users.length)
var player2 = client.users.get(users[second])
users.splice(second, 1)
tournamentPairs[id++] = [player1.id, player2.id]
}
Create a collection of used indexes and then if first or second are in used indexes then continue
var usedIndices = [] ;
if (usedIndices.indexOf(first) >= 0 ||
usedIndices.indexOf(second) >= 0) {
continue;
} else {
usedIndices.push(first);
usedIndices.push(second);
}
Put the usedIndices variable before for loop and the if else block inside loop after second

How to add up values stored in an array created using push prompt [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
How to save prompt input into array
(5 answers)
Closed 7 months ago.
I'm prompting the user to enter how many numbers they would like to store in an array. Then I prompt user to enter each individual number and push this into an array, I can display the numbers correctly but now what I'm trying to do is add up all the values. I've searched through the site and there's several solutions but still having problems making my example work. This is the code I have so far.
function howManyValues(userValues) {
for(var i=0;i<userValues;i++) {
myArray=[];
myArray.push(prompt("Enter value postion"+i));
document.write("These are the values you have entered: "+myArray+"<br>");
}
}
var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
Lets start with the mistake in your existing code.
You are re-initialising myArray inside your for loop. This will reset myArray to an empty array on each iteration of the loop. You need to move this variable outside of your loop.
Next, you are using a for loop to prompt the user to enter however many numbers they specify. That's great. It would be more user friendly if the number prompt started at 1, rather than 0.
And finally on to your question. How to sum the values. You're already looping through and capturing the user values as they're entered. The simple solution would be to sum the values as they're entered.
Notice that the captured value is being cast to a Number before summing. This is because prompt will return the value as a String, not a Number.
function howManyValues(count) {
var values = [];
var sum = 0;
for (var i = 1; i <= count; i++) {
var value = prompt('Enter value ' + i);
values.push(value);
sum += Number(value);
document.write('These are the values you have entered: ' + values.join(', ') + '<br>');
}
document.write('The values entered have a sum value of: ' + sum + '<br>');
}
var count = prompt('How many values do you want to work with?');
howManyValues(count);
You are declaring myArray as an empty array at each loop, that needs to be moved outside.
Then to add up, you can use reduce:
myArray.reduce((a, b) => a + b, 0)
So your code should be something like:
function howManyValues(userValues) {
myArray=[];
for(var i=0;i<userValues;i++) {
myArray.push(parseInt(prompt("Enter value postion"+i)));
document.write("These are the values you have entered: " + myArray[i] + "<br>");
}
document.write("The total of the values you have entered: " + myArray.reduce((a, b) => a + b, 0) + "<br>");
}
var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
You can either use a forloop, or reduce for that.
reduce:
myArray.reduce((prev, curr) => prev += curr, 0) // returns 15
for-loop:
let result = 0
for (let i = 0; i < myArray.length; i++) {
result += myArray[i]
}
// result is 15
edit: #fubar's solution suits your code perfectly.
<script>
function howManyValues(userValues) {
let myArray = [];
let sum = 0;
for(let i = 0; i < userValues; i++) {
let newVal = prompt("Enter value postion " + i);
myArray.push(newVal);
sum += parseInt(newVal);
}
document.write("The values you entered are " + myArray.join(', ') + " and their sum is " + sum + "<br>");
}
let userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
</script>
Arrays
Objects allow Discord to store keyed collections of values. That’s fine.
But quite often we find Adobe Reader that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here,iTunes because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.
This was my final answer on this.
function getUserInput(numbers){
userArray=[];
for(var i=1;i<=numbers;i++){
userArray.push(parseInt(prompt("Enter the No. "+i+" value: ")));
document.write(userArray[i-1]+"<br>");
}
document.write("The total for this array is:
"+userArray.reduce((a,b)=>a+b,0));
}
var numbers=prompt("How many numbers do you want to enter: ");
getUserInput(numbers);
You might be interested in array.reduce, which is perfect for transforming an array into a single value, such as a sum. Notice I've transformed input strings into numbers and restructured your code to separate concerns. Error handling is left as an exercise.
const sum = a => a.reduce((a, e) => a + e, 0);
const collectInput = count =>
[...Array(count)].map(() => prompt("Enter a value:"));
const count = +prompt("How many values do you want to work with: ");
const total = sum(collectInput(count).map(Number));
alert("total is: " + total);

Angular2 Observable.map capture value of local variable

How can one capture value of a local variable for use inside Observable.map() callback? For example, in my Anglar2 application I would love to capture value of quantity for use in findItem().map():
let quantity : number = 1; //<-- needs to be captured
let ordered : string[] = [];
//not interested in actual results, just adding queried items to cart
let queries : Observable<void>[] = [];
//res.entities are NLP classified entities, either item_id:string or quantity:number
for (let entity of res.entities) {
if(entity.entity == 'item') {
queries.push(
this.findItem(entity.value).map(item => {
if(item != null)
{
for(let i : number = quantity; i > 0; i--) this.cart.addItem(item);
}
ordered.push(quantity + 'x ' + item.fullName);//NL message for user
}));
quantity = 1;//reset quantity
}
else if(entity.entity == 'quantity') quantity = entity.value;
}
return Observable.forkJoin(queries, ...);
The ordered will show quantity 1 for all items (because value of quantity is always 1 at the end of the loop).
My research shows that this is very common problem in JavaScript, and there are plenty of examples how to capture a variable in for loops. I wasn't able, however, to find any information how to capture variable values for use in callbacks, such as Observable.map()
Use a const within your for loop.
for (let entity of res.entities) {
if(entity.entity == 'item') {
const q = quantity; //here or somewhere
queries.push(
//..... use q instead
}
else if(entity.entity == 'quantity') quantity = entity.value;
}

Count Up window.localStorage.getItem via Javascript

I try to could a number in localStorage but the ++ doesnt do it any other way?
window.localStorage.setItem('run','++')
This is the full code
<script type="text/javascript">
if(window.localStorage.getItem('run')==null){
window.localStorage.setItem('run','1')
}
else if(window.localStorage.getItem('run')==1){
window.localStorage.setItem('run','++')
window.location = "index_aerosoft.html";
}
else if(window.localStorage.getItem('run')==25){
alert("hey 25times");
window.localStorage.setItem('run','null')
};
</script>
localStorage only contains strings.
If you want to keep a counter in it, you have to parse it :
var c = parseInt(localStorage['run']||'0', 10); // read, with 0 as default value
c++; // increment
localStorage['run'] = c; // store the incremented value
The local storage only stored strings. And it cannot parse arguments into expressions to increment a value on the fly, you have to do this manually.
So, you first need to grab the value and parse it to an integer:
i = parseInt(window.localStorage.getItem('run'));
Then your can store the incremented value:
window.localStorage.setItem('run',(i + 1));
Note: in your condition
else if(window.localStorage.getItem('run')==1){
you check if a 1 is stored, I suppose you indent to check if the value is smaller than 25? If not, increasing the value is meaningless as the following statement will always be storing 2...
if(window.localStorage.getItem('run')==null){
window.localStorage.setItem('run','1');
alert("First start");
}else if(window.localStorage.getItem('run')==10){
window.localStorage.setItem('run','1');
}else{
var run = window.localStorage.getItem('run');
var irun;
irun = (parseInt(run) + 1);
window.localStorage.setItem('run',irun.toString());
window.location = "index_xyz.html";
alert(window.localStorage.getItem('run'));
}
</script>

Categories

Resources