Array equal two different values and change a variable dynamically - javascript

I want a user to key in an ID Number. When the user clicks on a button, the code will look for an array that has a list of all the id numbers to check if it exists. It will then go to check the price of that id number. Based on the price and what ID number was looked up I want this to change a variable called 'cost' dynamically. So for example, a user keys in the number "5555" The code looks up if the ID 5555 exists, if it does, it checks the price of that id. Based on that price, I want it to change a variable called cost. Likewise, if I looked up an id of "1234". It would look up the id, if it existed, got the price and then changed the variable called cost.
I don't even know where to begin with this. I was thinking about using arrays to map the id numbers and price but I don't know if that will work. I want a number to equal another number essentially and then change a variable based on the second number and I can't think of how to do that.
id[0] = new Array(2)
id[1] = "5555";
id[2] = "6789";
price = new Array(2)
price[0] = 45;
price[1] = 18;

You could use an object as a dictionary like object.
// Default val for cost
var cost = -1;
// Create your dictionary (key/value pairs)
// "key": value (e.g. The key "5555" maps to the value '45')
var list = {
"5555": 45,
"6789": 18
};
// jQuery click event wiring (not relevant to the question)
$("#yourButton").click(function() {
// Get the value of the input field with the id 'yourInput' (this is done with jQuery)
var input = $("#yourInput").val();
// If the list has a key that matches what the user typed,
// set `cost` to its value, otherwise, set it to negative one.
// This is shorthand syntax. See below for its equivalent
cost = list[input] || -1;
// Above is equivalent to
/*
if (list[input])
cost = list[input];
else
cost = -1;
*/
// Log the value of cost to the console
console.log(cost);
});

Related

Setting custom numeric key when pushing new data to firebase database

I am new to Firebase and I want to have my own keys while pushing new data to the database.
Right now I'm using the following.
uid(FirebaseAuth.getInstance().getCurrentUser().getUid())
But I want to create my own id and it must be a numeric value.
How can I create my own custom key there? Such as 0001,0002, etc.
I am asking here because I'm working on a project for online shopping. when a user adds a product to their inventory it needs to assign an id for every product. If it is not possible then just tell me no, I can accept that answer.
You can simply perform a push() function. What that would do is create a random id for your node.
databaseRef.push(); // You have created a node with a random id.
However, if you want to create a node with a numeric id you can have a function that creates a numeric value:
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
The function is from: 12 Digit unique random number generation in Java
You pass a length and it creates a random numeric value. The ideal length for you would be 5. Then you could go and do this:
long randomFiveDigitValue = generateRandom(5);
databaseRef.child(String.valueOf(randomFiveDigitValue)).setValue(your_object);
Another option would be to use an integer hash-code. It would decrease hash collisions, but you should be ready to handle them as with the previous function too. You could take an identifier from the order, like the date or even a mixture of factors, and do this:
//Replace all these variables with the respective value
String factors = "your_date" + "user_uid" + "product_name";
factors.hashCode(); //String date returns a integer hash value.
Here are the hashCode() collisions for 50000 randomly generated products:
COLLISIONS BETWEEN: 2 Items
ITEM 1: DATE: 24-5-2019 08:09 PM + NAME: IPHONE + UID: 4J3IF93KSKK0295[L3
ITEM 2: DATE: 24-5-2019 09:08 PM + NAME: MARKER + UID: 534KKJI903[PCO4OP5
It took a long time to generate these and I think collisions are really rare now. Like 1 to 50000 ratio. My algorithm could have been flawed, but still this way the collisions are really low.

Check whether any of multiple values exists in an array

(This question has been changed a bit since some of the answers were posted. That is why they might seem a bit off-topic and/or out of context)
Hello! So basically, I have this string that is entered by a user (a caption for an image, for example), and an array of links/words that I want to "block" the user from entering. (This would be to prevent from swearing, advertising etc.)
So I need some code that checks whether a certain value exists in an array.
This is my array:
var blockedUrls = ["https://google.com", "https://facebook.com"]
and this is the values I want to check
var userInput = "Hello! Check out my cool facebook profile at https://facebook.com";
(This would normally be set to a value fetched from an input of some sort, the static text is just to simplify)
So this is what I have tried:
let values = userInput.split(" ");
values.forEach((i, value) => {
// inArray is a made-up-function in order to better explain my intention
// The function I need here is a function that can check whether the value of the "value" variable exists in the "blockedUrls" array.
if(value.inArray(blockedUrls)) {
return alert(`You can't say that word! [${value}]`);
}
});
So a summary: How do I check if any of multiple values exists in an array?
You can check if a value is in an array by using indexOf
var value = document.getElementById('myFile').value;
if (unAllowedLinks.indexOf(value) != -1) {
// value is in array
}
-1 is returned when the value is not found in the array, else it returns the index of the value.
If you want to be able to change the number of values in unAllowedLinks you’d be better off using indexOf(), like so:
function updateImage() {
if (unAllowedLinks.indexOf(document.getElementById('myFile').value) > -1) {
alert("This link is reserved");
} else {
// Use the value
}
};

How to keep the localStorage values in html after refresh?

var btn = document.getElementById('insert'),
s = 0; //To increment the key(+1) each time the button is clicked and the user inputs the values so the first object's key is 1 then the second one is 2 and so on
btn.addEventListener('click', function() {
var ModelMake = prompt("Enter The Model Make"),
ModelYear = prompt("Enter The Model Year"),
Km = prompt("Enter The Amount Of Km"),
Price = prompt("Enter The Price"),
Status = prompt("Enter The Car's Status"),
table = document.getElementById('table');
var tableout = document.getElementById('tableout'),
FinalPrice,
Details;
localStorage.setItem(s += 1, JSON.stringify({
ModelMake: ModelMake,
ModelYear: ModelYear,
Km: Km,
Price: Price,
Status: Status,
FinalPrice: FinalPrice,
Details: Details
}));
This code inserts the following variables values(user inputs them) in a row and each value is in a column (cell), when i refresh the object IS stored in the localStorage even when i close my browser obviously but i want a way to keep it in the html whether i refresh or close the browser without having to extract it from the localStorage because i don't know how and it's not really what i want.
You could store your data in a cookie. Here is a tutorial that may be of use: Javascript and Cookies
If you want to do exactly, what you are asking I see few options for you:
on page load you can go thru all localStorage keys, find max number and assign it to S(Here is answer how to go thru all keys: Get HTML5 localStorage keys). I don't really like this way, but...
Store s value as separate key/value pair and extract it on page load

property undefined but console.log can see it

I am creating a dynamic form which consists of sku, qty and subtotal. So the form starts out from no inputs and filled up as the user searches for products. Upon keypress I need to compute the total quantity and show it to the user via javascript.
I am using getting all quantity input elements via getElementsByClassName upon keypress and counting all values. however the browser is returning an error (Uncaught TypeError: Cannot read property 'value' of undefined) but I can log the value.
I only use native JavaScript no jQuery.
qtyelements = document.getElementsByClassName('qty-element');
var x;
var count = 0;
for(x = 0; x <= qtyelements.length; x++){
console.log(qtyelements[x].value);
count = count + parseInt(qtyelements[x].value);
}
Here is an image of my
problem
Length gives you the number of items, but the collection is zero based. So for example while the length may be three, you only loop to two (0, 1, 2).
So change:
x <= qtyelements.length
to:
x < qtyelements.length
In your case it looks like you only have two elements, so the indices would be 0 and 1, but you check to see if 2 exists with the <=, hence the undefined.

Passing Variable length array to function Node JS

Is there a way to call an addon function with a variable length. I take the user input into a variable that looks like
Uinput = [5,3,2];
Now i want to call my addon based on these numbers so it would be
addon.myaddon(5,3,2);
I also want to extend this to n inputs so if my variable of user inputs becomes
Uinput = [5,3,2,6,...,n];
then the addon will be called like
addon.myaddon(5,3,2,6,...,n);
addon.myaddon(Uinput) // will not seperate the inputs by commas are they are in the array variable, it treats the whole array as the input
This seems simple enough but it is giving me a bit of trouble. Any tips ?
Take a look at Function.prototype.apply
Uinput = [5,3,2,...,7]; // the last number in the array is in position 'n'
addon.myaddon.apply(null, Uinput);
This is equivalent to calling:
addon.myaddon(Uinput[0], Uinput[1], Uinput[2], ... , Uinput[n]);
Real example using Math.max:
// Basic example
Math.max(1,6,3,8,4,7,3); // returns 8
// Example with any amount of arguments in an array
var mySet = [1,6,3,8,4,7,3];
Math.max.apply(null, mySet); // returns 8

Categories