while (line = readline()) - javascript

I'm new to JavaScript and are trying to solve a problem. I shall only write in JavaScript and the instructions are telling me to use readline(), for example like this: while (line = readline())
But I cant get how this works and I cant find any information about this in JavaScript. I want to get a users input and then put that in a variable. But when I try "while (line = readline())" I can's se anything happen (like with propt, which is the only way I know)...
Thankful for your help!
Here is my code (which works if I use alert and prompt istead of print and readline):
var usersNumber;
while (usersNumber = readline()) {
if (1 <= usersNumber && usersNumber <= 1000000000)
{
var inputBinary = usersNumber.toString(2);
var binaryArray = [];
for (i = 0; i < inputBinary.length; i++) {
binaryArray[i] = inputBinary.charAt(i);
};
binaryArray.reverse();
var stringBinaryFromArray = "";
for (i = 0; i < binaryArray.length; i++) {
stringBinaryFromArray = stringBinaryFromArray + binaryArray[i];
}
var digit = parseInt(stringBinaryFromArray, 2);
print(digit);
}
}

readline() is not a standard Javascipt function. You can use prompt() instead
while (usersNumber = prompt())
You might need to change the input from a string to a number.
while (usersNumber = Number(prompt()))
On another note, there are built-in functions you can use instead of the loops you have. split() and join(). You can even do it all in 1 line.
var stringBinaryFromArray = inputBinary.split('').reverse().join('');

(line = readline()) both assign line AND returns the value returned by readline()
if readline() returns null, line is null and the loop stops

Related

if variable equals else

Been trying all different ways of getting this to work. It's a Google spreadsheet script.
I get a error if a currency USDT comes up as there is no market BTC-USDT, it is USDT-BTC.
So I'm trying to make it set pair to altcoin+"-BTC" if the currency is USDT, Have tried multiple ways reading up different ways sometimes all I get it to do is USDT-BTC all the time, no other options.
This way I just get a error but it gives a better idea with what I'm trying to do.
for (var i = 1; i < currencyarray.length; i++) {
var altcoin = currencyarray[i][0];
{
if (altcoin = "USDT") {
var pair = altcoin+"-BTC";
else {
var pair = "BTC-"+altcoin;
}
//sheet.getRange((1+i), 3).setValue(pair);
//sheet.getRange((1+i), 4).setValue(currencyarray[i][1]);
sheet.getRange((1+i), 5).setValue(currencyarray[i][1]);
}
}
opps, sorry forgot extra =. Have changed it a little but when it gets to USDT it does BTC-BTC not USDT-BTC, Sorry I'm not a full time coder, try to teach myself.
for (var i = 1; i < currencyarray.length; i++) {
var altcoin = currencyarray[i][0];
{
if (altcoin == "USDT")
pair = altcoin+"-BTC";
else pair = "BTC-"+altcoin;
}
sheet.getRange((1+i), 5).setValue(currencyarray[i][1]);
var lastprice = bittrexGetlastprice(pair);
var value = (currencyarray[i][1]*lastprice);
sheet.getRange((1+i), 5).setValue(value);
}
In this line
if (altcoin = "USDT") {
You set altcoin to USDT, which counts as a truthy value, so the body of this if always runs. Use == when comparing
if (altcoin == "USDT") {
This works,
use == in if condition.

javascript getElementById function not working

I tried the following: it is working fine
function saveTitle(index,id){
arrtitle[1] = document.getElementById("title_1").value;
arrtitle[2] = document.getElementById("title_2").value;
arrtitle[3] = document.getElementById("title_3").value;
}
but as I tried the following:
function saveTitle(index,id){
for(i=1;i<=count;i++)
arrtitle[i] = document.getElementById("title_"+i).value;
}
It gives me an error that : Uncaught TypeError: Cannot read property 'value' of null
Please suggest me something. Thanks...
You can use querySelectorAll to get all the elements that contains "title_" string . See the bellow code.
function getTitles() {
var arrtitle = [];
var elements = document.querySelectorAll("*[id*='title_']");
for (i = 0; i < elements.length; i++) {
var titleId = elements[i].id.replace("title_", "");
arrtitle[titleId] = elements[i].value;
}
return arrtitle;
}
getTitles();
Based on what you've posted, if that's your actual code, the only possibility seems to be that count is higher than the maximum element that exists (or there's a hole). For example, count might be 4, and there is no element with the id of title_4.
The javascript debugger would help you find this pretty easily.
I'd also suggest using braces around the body of your for loop, which would significantly help readability.

Need help in converting C++ to javascript

I'm constructing a javascript indicator for my client and they gave me below C++ code from their old system. I have never done C++ program before. Below is the part of the C++ code. What I want to know is in the line
if (it3 != d1Swing.end() && it3->x == h[i].x) --(it1 = it2 = it3); what is the meaning of --(it1 = it2 = it3)? What will it looks like in javascript?
vector<PTPoint::PTIndexPoint> dnSwing;
list<PTPoint::PTIndexPoint> hq, lq;
vector<PTPoint::PTIndexPoint>::iterator it1 = d1Swing.begin(), it2 = d1Swing.begin(), it3 = ++d1Swing.begin();
//
// more code here
//
for (int i = 0; i < period; ++i)
{
while (!hq.empty() && hq.back().y < h[i].y) hq.pop_back();
hq.push_back(h[i]);
while (!lq.empty() && lq.back().y > l[i].y) lq.pop_back();
lq.push_back(l[i]);
if (it3 != d1Swing.end() && it3->x == h[i].x) --(it1 = it2 = it3);
//
// more code here
//
}
//
// more code here
//
p->swap(dnSwing);
Thanks in advance.
tslin
It means that their previous programmer loved being "clever".
The value of an assignment is a reference to the object that was assigned to, and assignment associates to the right.
--(it1 = it2 = it3)
is
--(it1 = (it2 = it3))
and it's intended to assign the value of it3 to it2 and it1, then decrement it1.
(I have a hunch that this may be undefined, which is a thing that happens frequently when you're being clever in C++.)
it1 is apparently intended to be "one step behind" it2.
A more reasonable way to write that is
it2 = it3;
it1 = it2 - 1;
(In JavaScript, I suspect that you need to work with array indices rather than iterators to accomplish the same thing.)

Creating a new function that takes default arguments for another function (Javascript)

I am currently trying to create a defaultArguments function that takes in a function and some parameters that are set as default values. The steps I am thinking about taking to solve this particular problem is to:
Parse through the function in order to obtain what its arguments which could be anything.
Go through each argument that was extracted and replace arguments that have input parameters to its respective value.
Now, what I was thinking about doing next was to add additional default arguments into the input 'func'. I tried to:
Look up how to input a string as an argument into an existing function. However, the function then just reads the argument string as just a string.
Use the JavaScript .apply method. However, I won't always have all input values.
Here is the code I wrote so far.
function defaultArguments(func, params) {
var reg = /\(([\s\S]*?)\)/;
var extractVar = reg.exec(func);
if (extractVar) {
var arguments = extractVar[1].split(',');
}
for (i = 0; i < arguments.length; i++) {
if (params[arguments[i]]) {
arguments[i] = params[arguments[i]];
}
}
}
So for example, if I have a function
function add(a,b) { return a+b; };
I would use the defaultArguments function as such
var add_ = defaultArguments(add,{b:9});
console.log(add_(10) === 19); // b is defaulted to 9
console.log(add_(10,7) === 17); // b is given so use given value
console.log(add_()); // NaN
I would love some hints as to how to solve this problem and a different approach if I am approaching this problem incorrectly. I appreciate your time for reading this and I hope to see your response!
UPDATE:
So I was able to come up with a rough solution for this question. I was wondering if I approached the problem correctly and if there's any improvements do to my code. After researching a lot, I know that I shouldn't use eval(), but I don't know how else to tackle the problem. I am open to suggestions. Thanks in advance!
function defaultArguments(func, params) {
var stringed = func.toString();
var inputs = stringed.match(/\(.+\)/)[0].replace("(", "").replace(")", "").split(",")
for (i = 0; i < inputs.length; i++) {
inputs[i] = ""+inputs[i]+" = "+inputs[i]+" || "+params[inputs[i]]+";"
}
for (i = 0; i < inputs.length; i ++) {
stringed = stringed.replace("{", "{ "+inputs[i]+"")
}
var newFunc = "var restoreFunc = " + stringed;
eval(newFunc);
return restoreFunc;
}

I am getting Error from For Loop function in Javascript

this is a function to call SELECT element values. but i am facing an error.
code is here.
function get_s_val(){
var foo = all_categories_1;
var ov1 = "";
for(m=0;m<=foo.length;m++){
ov1 += foo[m].value+',';
}
console.log(ov1);
var tme=setTimeout("get_s_val()", 1000);
}
get_s_val();
it shows an error like "Uncaught TypeError: Cannot read property 'value' of undefined"
but when i do some littel changes it works.. like
function get_s_val(){
var foo = all_categories_1;
var ov1 = "";
//for(m=0;m<=foo.length;m++){
ov1 += foo[0].value+',';
//}
console.log(ov1);
var tme=setTimeout("get_s_val()", 1000);
}
get_s_val();
i dont know that where i am wrong to write the code.
Modify your loop condition to run while the iterator is less than the length of the array, or you'll get undefined when you hit the non-existent element at index foo.length:
for(var m=0;m<foo.length;m++){
ov1 += foo[m].value+',';
}
...and always declare variables with the var keyword, or bad things will happen, and JSLint will whine about it (and rightly so, but that's another topic).
function get_s_val(){
var foo = all_categories_1;
var ov1 = "";
for(var m = 0; m < foo.length; m++){ // use var, and only loop from e.g.
// 0 to 2 when the length is 3, so <,
// not <=
ov1 += foo[m].value+',';
}
console.log(ov1);
setTimeout(get_s_val, 1000); // don't use a string, just pass the function.
// Plus, the variable is nowhere accessible so
// you can drop storing it
}
get_s_val();
Anyway, if you simply want to join the array's elements into a string with , as delimiter, why not do:
console.log(foo.join());
At the top of the for loop, m<=foo.length; should instead be m<foo.length;.

Categories