How do I add commas in between the inputs to make the function work?
function square(num) {
var items=str.split("")
return Math.abs(num*num - num2*num2)
}
square(4 2);
You can use
function square(num, num2) {
return Math.abs(num*num - num2*num2);
}
console.log(square(4, 2));
console.log(square(2, 4));
You can use Math absolute function:
function square(num, num2) {
var sq1 = num * num,
sq2 = num2 * num2;
return Math.abs(sq2-sq1);
}
To handle the problem that you didn't include in your question, you can pass a string into the square function, and handle like so:
function square(NUMBERS_STRING) {
var numbers = NUMBERS_STRING.split(" "),
sq1 = numbers[0] * numbers[0],
sq2 = numbers[1] * numbers[1];
return Math.abs(sq2-sq1);
}
Please, don't confused square("4 2") with square(4 2).
The second is not valid javascript.
May be worth pointing out that calling this function "square" may be a bad idea. If someone isn't used to your code and they see this function, are they going to know what it does outright? Maybe diffOfSquares(num, num2)?
My recommendation is to have the real mathematic function that'd be reusable in 99% of use cases:
function square(num, num2) {
num *= num;
num2 *= num2;
return Math.abs(num-num2);
}
And then for your overload call the above. Reason for this is that if something were to ever happen and the underlying logic found in function square(num, num2) required modifying, you would only modify it in one case and not for it plus every other overload. Here's how I'd do it for your current case:
function square(str) {
var items = str.split(" ");
return square(items[0], items[1]);
}
Optionally, but for the sake of reusability, what happens in the future if we get a string where they're pipe delimited? Comma delimited? I wouldn't want to break the code that assumed spacing, so I might modify that function to be:
function square(str, delim = " ") {
var items = str.split(delim);
return square(items[0].trim(), items[1].trim());
}
So if I call it, I could do:
square("4 2", " "); // space delimited
square("4 2"); // space delimited for legacy items
square("4, 2", ","); // comma delimited
square("4|2", "|"); // pipe delimited
Related
I have a simple JS function
let a = 0.33, c=13.89;
var res = calcRound(c*2+calcRound(a*2,1,1),1,1);
console.log(res);
function calcRound(value, figure, padding) {
let val = value;
let result = parseFloat(val);
result = result.toFixed(figure);
return result;
}
It returns a 27.8. But the answer should be 28.5
I have debugged the code. At first, it calculates this and it is correct
calcRound(a*2,1,1) = 0.7
Second time the '+' operator between c*2 and calcRound(a*2,1,1) gets lost.
it becomes like this 27.780.7 which should be like this 27.78+0.7
I know JS first evaluates the expression before sending it as an argument. My question is why the '+' operator is getting omitted?
+ is the concatenator operator in JS, it thinks the result from calcRound() is a string and behaves accordingly.
As mentioned by Andy in the comments, you can see in the
documentation for toFixed()
Return value: A string representing the given number using fixed-point
notation.
Change the return of your function to (to make sure it returns a number):
return Number( result );
let a = 0.33,
c = 13.89;
var res = calcRound(c * 2 + calcRound(a * 2, 1, 1), 1, 1);
console.log(res);
function calcRound(value, figure, padding) {
let val = value;
let result = parseFloat(val);
result = result.toFixed(figure);
return Number(result);
}
It's not getting omitted, JavaScript is treating them like strings and adding 27.78+0.7 as strings, you want to surround them in Number() or parseFloat() statements so that they are treated as numbers.
Like so:
calcRound(parseFloat(c*2) + parseFloat(calcRound(a*2,1,1)),1,1)
I want to do aggregation operation by identifying "sum(a)" as in the below string and need to perform some logical operation to get sum, avg, count or percentage(i have separate method to do that so don't worry about that).
expression like below,
= '"sum(a)" * 10 + "count(b)"'
Here a and b is key word. Based on the key word i will perform the operation. But i need to identify operation name and key word in the above string.
Then, I need to execute the expression without using eval function for following expression. like below,
"10 * 10 + 22"
Note: I am trying to use Function constructor, but i am facing performance issue.(Use string to call function without eval())
You can use Array.proptotype.reduce:
const values = [2,3,4];
const sum = values.reduce((sum, current) => sum + current, 0);
console.log(sum * 10 + values.length);
function sum(values){
return values.reduce(function(s, n){
return s + n;
}, 0)
}
function count(values){
return values.length
}
alert( sum([2,3,4]) * 10 + count([2,3,4]) )
I'm currently stuck on a Codewars challenge that I can't get my head around:
Given a string representation of two integers, return the string representation of those integers, e.g. sumStrings('1','2') // => '3'
I've used the following code so far, but it fails on large number test cases as the number is converted into a scientific notation:
function sumStrings(a,b) {
var res = +a + +b;
return res.toString();
}
Any help would be much appreciated.
Edit:
Fiddle example: https://jsfiddle.net/ag1z4x7d/
function sumStrings(a, b) { // sum for any length
function carry(value, index) { // cash & carry
if (!value) { // no value no fun
return; // leave shop
}
this[index] = (this[index] || 0) + value; // add value
if (this[index] > 9) { // carry necessary?
carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go on
this[index] %= 10; // remind me later
}
}
var array1 = a.split('').map(Number).reverse(), // split stuff and reverse
array2 = b.split('').map(Number).reverse(); // here as well
array1.forEach(carry, array2); // loop baby, shop every item
return array2.reverse().join(''); // return right ordered sum
}
document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');
The problem is that in that specific kata (IIRC), the numbers stored in a and b are too large for a regular 32 bit integer, and floating point arithmetic isn't exact. Therefore, your version does not return the correct value:
sumStrings('100000000000000000000', '1')
// returns '100000000000000000000' instead of '100000000000000000001'
You have to make sure that this does not happen. One way is to do an good old-fashioned carry-based addition and stay in the digit/character based world throughout the whole computation:
function sumStrings(a, b) {
var digits_a = a.split('')
var digits_b = b.split('')
...
}
Why would we declare a second variable (val) when we can use the parameter of the function as a variable?
Here's how it looks like on codecademy:
var divideByThree = function (number) {
var val = number / 3;
console.log(val);
};
divideByThree(6);
I've made some changes as below:
var divideByThree = function (number) {
number = number / 3;
console.log(number);
};
divideByThree(6);
And it works pretty fine!!
In your example, you do not need to preserve the original value of the parameter. However, you may find it easier to use extra variables in the future for more complicated functions.
Here is an example:
// This function uses the parameter "rawNumber" as a variable, but also uses an extra variable "number"
function TestThis(rawNumber, p) {
// Convert the input (string) to integer
// parseInt returns NaN or integer. Truncates decimals
var number = parseInt(rawNumber);
// Check to see if the result is NaN or is an integer
if (isNaN(number)) {
Log(rawNumber + " is not a number.", p); // Log is my imitation of console.log()
}
// will run if number is type int
else {
if (number > 0 && number <= 100) {
Log(rawNumber + " is a valid number.", p);
} else {
Log(rawNumber + " is not between 1 and 100.", p);
}
}
}
You can see this code working in this Fiddle.
In this function I used an extra variable called "number" in three different places. I didn't have to, but it was easier than typing isNaN(parseInt(rawNumber)) and if(parseInt(rawNumber) > 0 && parseInt(rawNumber) <= 100). Codecademy was probably decided to teach you this way because it is easier to realize you can simplify your code than to realize you can simplify a more complex code through the use of extra variables.
Also, JK Price's answer brings up a readability issue. Simply put, this code is easier to read and understand:
function Example(number) {
var processedNumber = 5/(Math.log(1/number*3.14 - 7));
console.log("Message: " + (processedNumber * 2));
console.log("Message: " + (processedNumber / 10));
}
This code might be a little harder:
function Example(number) {
console.log("Message: " + ((5/(Math.log(1/number*3.14 - 7)) * 2));
console.log("Message: " + ((5/(Math.log(1/number*3.14 - 7)) / 10));
}
Variables are supposed to help the programmer write better and describe a better story. You can't have the same actor play multiple characters! One thing it does is to help keep variables separate.
The variable val in this case helps abstract the logic and most importantly help in debugging. If this was a long script and you saw that number was not what you originally passed it, you might consider it to be an error.
Been running into some problems with returning the computed value of a function that is inside an array. and would appreciate any help in solutions as well as advice about more elegant ways of approaching this type of problem (i.e. a more logical way to have solved this)
I'm trying to create a program that generates two random digits and a random operator to apply to said digits.
var num1 = Math.floor(Math.random() * 20 + 1);
console.log(num1);
var num2 = Math.floor(Math.random() * 1000 + 21);
console.log(num2);
I originally set my random operator this way:
var ops = ["+", "-", "*", "/"]
I tried to use a Math.random function to select a random index number for the ops array, but was getting all kinds of errors, so I started searching and found some helpful advice here: How to use Javascript to ask the user random math questions?, but couldn't figure out a way to retrieve a random value from the object,(cf. Access non-numeric Object properties by index?) so I changed back to using an array of 4 functions, each of which has a return value that computes the random numbers (num1 and num2) based on the random operator.
I've gotten everything to work (i.e. have tested my random number functions are working, and even see that my newOp variable is returning a different function from the ops array each time), but here's what I can't get the program to do: return the computed value of the function. When I
alert(newOp)
I want it to alert the function's value instead of the function itself. (e.g. alert -> 20 instead of what I'm currently getting: --> function a(){return (num1 + num2)}
Here's my code. All advice and insight welcome! Just trying to learn.
var num1 = Math.floor(Math.random() * 20 + 1);
console.log(num1);
var num2 = Math.floor(Math.random() * 1000 + 21);
console.log(num2);
var ops = [
function a(){return (num1 + num2)},
function b(){return (num1 - num2)},
function c(){return (num1 * num2)},
function d(){return (num1 / num2)}];
var problem = function () {
var random = Math.floor(Math.random()* 4 + 0);
var newOp = ops[random];
alert(newOp);
};
problem();
I think you just need to change it to:
alert(newOp());
Your array contains references to the functions, but you're not invoking them.
I think you are just missing the actual invocation.
Change alert(newOp); to alert(newOp());