JavaScript command line calculator - javascript

I want to made calculator without buttons.
Can you help me with function calculate?
I have two arrays, first array with numbers, and second with arithmetic operators.
In function calculate I must send one element from first array and one from second, but it dont work. In final program must give answer as number.
Can you explain me method reduce, can i send second array as a parameter?
Because in docs i find that it only sum elements.
Ill be very grateful if somebody write example of method reduce with function.
Here is my code.
var str = ("1+1+1+1-1*3");
var reg = /(\d+\.\d+)|\d+/g;
var myArray = str.match(reg);
var reg1 = /['+','-','*',"/"]/g;
var myArray2 = str.match(reg1);
console.log(myArray);
console.log(myArray2);
var i = 0;
function calculate(prev,curr,i){
if(myArray2[i] === "+"){
//
curr = parseInt(prev,10)+parseInt(curr,10);
}
else if(myArray2[i]==='-'){
//
curr = prev-curr;}
else if(myArray2[i] ==='*'){
//
return prev*curr;
}
else{
//
return prev/curr;
}
}
var finAns = myArray.reduce(calculate);
alert ("Answer = " +finAns);

Yes, you can use reduce (see MDN) with your own function, but here you have some errors :
you should start calculation at index 1 since for the first element (index = 0), you have curr = prev = the first element (here 1)
your regex does not match the symbol - (you should escape it)
I have made a jsfiddle : http://jsfiddle.net/6UyUq/.
EDIT : it does not take into account operators precedence as showed in #Jim Wharton's comment.....

Related

What am I doing wrong in this Twilioquest exercise? (sortOrder.js - JavaScript Begin)

well, this is the problem:
(TwillioQuest - Enable Beam 2 Problem)
Create a script called sortOrder.js. This script will take two command
line arguments - a pair of strings that should be compared to see
which one comes first alphabetically (letter casing is not important).
To test your script, you would execute it like this:
node sortOrder.js cats dogs
Your script should determine if the first string is before, after, or
in the same position (equal) to the second string, alphabetically. For
each case, you should print out a number with console.log as described
below.
When the first argument is earlier in the alphabet than the second, your script should print -1.
When the first argument is the same as the second, your script should print 0.
When the first argument is later in the alphabet than the second, your function should print 1.
Basically, cats and dogs must output -1, dogs and cats output 1, dogs and dog outputs 0. It must ignore case sensitive.
Then, I tried two different approaches:
1- Creating two lists (one before the sorting method and one after) and printing in sequence with IFs:
let aftSort = [];
let bfSort = [];
const first = process.argv[2].toLocaleLowerCase();
const second = process.argv[3].toLocaleLowerCase();
aftSort.push(first);
aftSort.push(second);
bfSort = [...aftSort];
aftSort.sort();
if (bfSort[0][0] == bfSort[1][0]){ //checking if the first letters are the same
console.log(0)};
if (bfSort[0] == aftSort[0]) { //checking if the first word is still first after sorting
console.log(-1)};
if(bfSort[0] == aftSort[1]){ //checking if the first word is the second after sorting
console.log(1)};
2- Creating the same lists but printing only once after an analyze function:
let aftSort = [];
let bfSort = [];
const first = process.argv[2].toLocaleLowerCase();
const second = process.argv[3].toLocaleLowerCase();
aftSort.push(first);
aftSort.push(second);
bfSort = [...aftSort];
aftSort.sort();
function analyze(aftSort,bfSort) {
if (bfSort[0][0] == bfSort[1][0]){ //in case bothe initial letters are the same
console.log(0);
return;}
else {
if (bfSort[0] == aftSort[0]) { //in case the initial string is in the first position after sorting
console.log(-1);
return;} else if (bfSort[0] == aftSort[1]) { //in case the initial string is in the second place after sorting
console.log(1);
return;}
}
}
analyze(aftSort,bfSort);
Edit: Now, even a third method using only the first letters and no list which also doesn't work:
const firstValue = process.argv[2].toLowerCase();
const secondValue = process.argv[3].toLowerCase();
function analyze(firstValue, secondValue) {
if (firstValue[0][0] == secondValue[0][0]) {console.log(0)} //comparing first letters
else {
if (firstValue[0][0] < secondValue[0][0]) { //comparing the values
console.log(-1)}
else if (firstValue[0][0] > secondValue[0][0]){console.log(1)};
}
}
analyze(firstValue, secondValue)
However, even passing my own tests, I keep receiving this error in the game:
Your script must print "1" when the first argument passed to it
appears alphabetically later than the second argument.
Can anyone help with this?
Try this:
const firstValue = process.argv[2] //leave it like this. No .toLowerCase()
const secondValue = process.argv[3] //same here. No .toLowerCase()
let result = 0; //to have the result stored here.
within if and else if you can compare firstValue.tolowerCase() and secondValue.toLowerCase()
update your Variable 'result' by -1 or 0 or 1, depending on the comparison.
don't forget to display result with console.log at the end.
Just tried the third approach again, but not considering only the first letters:
const sortFirstArg = process.argv[2].toLocaleLowerCase();
const sortSecondArg = process.argv[3].toLocaleLowerCase();
let answer = 0;
if (sortFirstArg < sortSecondArg){
answer = -1;
}
if (sortFirstArg > sortSecondArg){
answer = 1;
}
console.log(answer);
Apparently they don't want a real alphabetical order...
Edit: This one worked.

Create a variable with two arrays made from two .map() looking for match or intersection

The point is I'm not an expert with JS so excuse me if my code is a big mistake, in fact I'm just training to learn making a huge "Frankenstein" from a research around the web.
I want to take two set or lists of values input by the user and compare them looking for matches with js and jquery.
First, I take the values from two groups of inputs (diferenced by class) with .map(), this to have the values to create the arrays.
var x = $(".row_a").map(function() {
return this.value;
}).get();
var y = $(".row_b").map(function() {
return this.value;
}).get();
Then I'm traying to create one variable that contain the two arryas separatly (here Is when think I have the problem) if I "hardcode" the arrays the next part of the script works as expected, but if I use the the first two variables made above, the script just crash.
var arrays = [
[x],
[y]
];
In the third part (I really don't understand this part of the code in deep) I run the script that compare the two arrys on the second variable and then append a paragraph with the result.
var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
Somebody can help me to undersnatd whats wrong or giveme a clue or link that can help?
curious: if I use the same variable twice in the variable that contain the arrays, the script works and finds four matches (I think is right becouse compare the same array)
DEMO
--
EDITED:
Thanks to #KarlReid and #Potorr. I didn't know the intersection concept in javascript, so now I know a better way to achive the result. I'll read more about it to try understand the answer in deep.
Thanks to #Alexandru for letting me know the sintax error, it'll be very basic and usefull henceforth.
Final Result: DEMO
(I'll be edit the tittle of the post to try improve the search for others with the same question in the future.)
This works, explanation in-line:
$(".action").click(function() {
var x = $(".row_a").map(function() {
return this.value;
}).get()
var y = $(".row_b").map(function() {
return this.value;
}).get()
// this is not really needed, if you want it:
// x, y are already arrays, so you don't need to wrap them with []
// var arrays = [
// x,
// y
//];
// intersection, adapted from: https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
// if you use the "arrays" variable, then change x to arrays[0] and y to arrays[1]
//var intersection = x.filter(function(n) {
// return y.indexOf(n) !== -1;
//});
// the intersection function posted by #KarlReid is actually better and faster:
var intersection = x.filter(Set.prototype.has, new Set(y));
// create the result string
var result = intersection.join(',')
$(".match").append("<div>Numbers " + result + " match in both lists</div>");
});
Edit: Changed intersection function to the one posted by #KarlReid
Although better solutions exists, as pointed out by comments the Potorr's answer, the only problem with the code posted is this:
var arrays = [
[x],
[y]
];
x and y are already arrays, so you don't need to wrap them with [ ]. The code works if you simply replace the above code with:
var arrays = [
x,
y
];
Updated demo

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.

Trying to search through array of strings for a pattern the user inputs - javascript

var p = ["array of words", "i really hate the sun", "i'm TIred"]
function findword(contents,pattern){
var answer;
var idx;
var counter = 0;
var pat_lc = pattern.toLowerCase();
for (var i = 0; i <= contents.length-1; i++){
var str_lc = contents[i].toLowerCase();
idx = str_lc.indexOf(pat_lc)
if (idx >= 0){
answer = i
}
else{
answer = "-1"
}
}
alert(answer)
}
findword(p,"words")
I'm trying to find the index of the array for a certain word, in an array of strings, however it only works for certain words in the array above. For example, on the last line of the code, when I chose to search for "words" it returns the value of "answer" and "idx" -1 when it should be 0 and 9 respectively. However, when I search for "tired", the value of "answer" is 2 and "idx" is 4 (which is correct). Why do some words work and others return the value of -1?
Here's a modified working version that will find all matches
var p = ["array of words", "i really hate the sun", "i'm TIred"]
function findword(contents,pattern){
var matches=[];
var idx;
var pat_lc = pattern.toLowerCase();
for (var i = 0; i <= contents.length-1; i++){
var str_lc = contents[i].toLowerCase();
idx = str_lc.indexOf(pat_lc)
if (idx >= 0){
matches.push({ idx: i, position: idx})
}
}
return matches
}
Several problems
answer and idx get overwritten ever pass of the for loop. So regardless if a match was found...only last pass is returned. I saved the results into separate array that gets returned. Code you provided didn't do anything with idx.
Can test output for length to see if matches exist...no matches will return empty array with no length
Come to think of it...not sure what output you want
DEMO
You should stop as soon as you find a solution.
Your program only stops when it iterated over the whole array. But what if the answer what not in the last element ? Then answer will contain -1.
You can init answer at -1 and continue your for loop as long as i is less than content.length and answer is equal to -1 : http://jsfiddle.net/#&togetherjs=dbVcN8JkKP

Want to add a value and remove on a single click using javascript or jquery

I am using a onclick function and adding a value to by paasing a value to it. If the value already exists den i remove that value from the list.
function send_value(str)
{
//alert(str);
var sub_id = document.getElementById('selected_sub_id').value;
//alert(sub_id.indexOf(str));
if(sub_id.indexOf(str)==-1)
{
if(sub_id=="")
{
sub_id+=str;
}
else
{
sub_id+=',';
sub_id+=str;
}
}
else
{
sub_id = sub_id.replace(str+",", "");
sub_id = sub_id.replace(","+str, "");
sub_id = sub_id.replace(str, "");
}
//alert(sub_id);
document.getElementById('selected_sub_id').value=sub_id;
}
This is the function. Suppose i have the values 1,2,3,4 in the selected_sub_id and i am passing 5 to it, it will be stored as 1,2,3,4,5
now i am passing 24 it will be stored as 1,2,3,4,5,24
No suppose i want to remove 2, so when i send 2 to the function it removes all the occurrences of 2 so i am left with only 1,3,4,54...
kindly help me with this thanks in advance..
You most probably want an array for this. It makes things much easier.
Create one first:
var arr = [];
Adding goes with .push:
arr.push(24);
Removing goes with .splice and .indexOf (the 1 means 'removing 1 element'):
arr.splice(arr.indexOf(24), 1);
Converting to a string goes with .join:
arr.join(); // 1,2,3,24 or something similar depending on elements
For example: http://jsfiddle.net/ScBNQ/.
var arr = [];
// adding
arr.push(1);
arr.push(2);
arr.push(3);
arr.push(24);
// removing
arr.splice(arr.indexOf(2), 1);
// joining
arr.join(); // 1,3,24

Categories

Resources