Calculate sum of props from TextInput - reactjs

I want to calculate the sum of the props I'm passing to my child component but it seems to only work when I add them in the correct order. Ex. I enter math as 100, science as 100, and so on down the line, it will add correctly. But if I enter math as 100 then art as 100, totalscore will show as 100100 and not 200.
For example:
var totalScore =
this.props.math +
this.props.science +
this.props.history +
this.props.gym +
this.props.lunch +
this.props.art
if (e == 1 || e == 2 || e == 3) {
if (isNaN(totalScore)) {
return totalScore = 'fail';
} else {
return totalScore
}
}
How can I add a value these props in any order with the correct sum?

The problem is not with the order and the order is NOT important. The problem is string concatenation. You are passing string instead of numbers
Explicity typecasting them like below should fix the issue
var totalScore =
Number(this.props.math) +
Number(this.props.science) +
Number(this.props.history) +
Number(this.props.gym) +
Number(this.props.lunch) +
Number(this.props.art)
if (e == 1 || e == 2 || e == 3) {
if (isNaN(totalScore)) {
return totalScore = 'fail';
} else {
return totalScore
}
}
For reference, to pass the props as numbers, do this
<Component someProp={100} >
if you say someProp="100" it will be a string

it seems like the props is a string because the number you enter are concatenated. You can use the parseInt or parseFloat functions, or simply use the unary + operator:
example
var totalScore =
parseInt(this.props.math) +
parseInt(this.props.science)
Or
+this.props.science +
+this.props.math
Or
parseFloat(this.props.math) +
parseFloat (this.props.science)
in short You need to convert the string to number

Related

While adding two numbers getting NAN as output in the react?

When I am trying to add two numbers, I am able to get NaN. If anyone has any advice, any help would be greatly appreciated.
This is my Code:-
var sum = parseInt(label.labellength, 10) + parseInt(label.labely, 10);
console.log("Sum of FrontRight is " + sum );
Output is:-NaN
I tried as following :
Using Number
var sum=Number(label.labellength) + Number(label.labely);
Output is:-NaN
The same issue came to me , try to use || operator and return it, it did the same and it worked for me...
const [contextOverHr,setContextOverHr=useState("")
return (
{Object.values(workHour).reduce((pre,total) => {
let totalNum = pre + total.OverHour
setContextOverHr (totalNum)
return totalNum || 0
},0)
}
)

Sort Numbers after Letters in Angular

I want to sort Letters first and followed by numbers like below:
[Austria , France , Germany , 101110 , 124563]
This is what i have tried:
obj.sort((a,b) => a.text > b.text ? 1 : -1)
But it is sorting numbers first and then letters.
Any help?
If you are looking for a solution like you want to sort string at the first portion of array and numbers at the last of array, just make sure that you are following this procedure.
Never compare a string with a number.
If both a and b are string or both are numbers just compare both with a > b and return 1 or -1 depending on the result of comparision.
The last else block corresponds to the comparision between a number and a string. The return value determines the location of the numbers in the array. If either one of them is not a number, return -1 or 1 depending on the requirement. Since you want the numbers at the end of your array, return -1 if the value is not a number. If you send 1 instead, the numbers will take the first posion in he output array.
const data = [101110 , 124563 , 'France' , 'Austria', 'Germany'];
const output = data.sort((a,b) => {
if (
(isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b))
) {
// Both are strings
// OR
// Both are numbers
return a > b ? 1 : -1;
}
else {
// One of them is a number
return isNaN(a) ? -1 : 1;
}
});
console.log(output);
Much Simplified version
const data = [101110, 'France', 'Austria', 124563, 'Germany'];
const checkOfSamePattern = (a, b) => (isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b));
const output = data.sort((a, b) => checkOfSamePattern(a, b) ? a > b ? 1 : -1 : isNaN(a) ? -1 : 1);
console.log(output);

Second argument replacing first scala

I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like
2
x
Here is what I have so far...
class $ (val text2D: Array[Array[Char]])
{
def ^(that: $) =
{
" " ++ s"${this.text2D(0)(0)}" ++
"\n" ++ s"${that.text2D(0)(0)}"
}
def +(that: $) = this.text2D + "+" + that.text2D
override def toString = s"${this.text2D(0)(0)}"
}
object $ {
val array = Array.ofDim[Char](1,1)
def apply(x: String): $ = {
array (0)(0) = x.charAt(0)
new $ (array)
}
}
val x = $("x")
println(x)
val x2 = $("x") ^ $("2")
println(x2)
When I run this, I do not get the output I am expecting, instead I get
2
2
Why is it only taking the second element? Any help would be appreciated.
object creates a singleton, so the (mutable) array that you use is shared between calls to apply. You need to allocate that array inside the apply call.
def apply(x: String): $ = {
val array = Array.ofDim[Char](1,1)
array (0)(0) = x.charAt(0)
new $ (array)
}
Also, slightly unrelated, but I believe you have your arguments backward. To get the output you want, you need
" " ++ s"${that.text2D(0)(0)}" ++
"\n" ++ s"${this.text2D(0)(0)}"
I think what you need is something like this:
class $(val text2D: Array[String]) {
def ^(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// cross-pad arrays to have the same width
val padThisRight = " " * thatW
val padThatLeft = " " * thisW
val thisPaddedW = this.text2D.map(_ + padThisRight)
val thatPaddedW = that.text2D.map(padThatLeft + _)
// first lines comes from that!
new $(thatPaddedW ++ thisPaddedW)
}
}
def +(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisH = this.text2D.length
val thatH = that.text2D.length
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// pad arrays to have the same height
val emptyThis = " " * thisW
val emptyThat = " " * thatW
val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D
new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
}
}
override def toString = text2D.mkString("\n")
}
object $ {
def apply(x: String): $ = {
new $(Array[String](x))
}
}
and then
val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")
val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")
val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")
produces following output
x2:
2
x
----------------------------
z:
2 2
x + y
----------------------------
zz:
3
2 2
x + y
----------------------------
The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.

Merge random elements of array/split into chunks

How can I split array into chunks with some special algorithm? E.g. I need to shorten array to the size of 10 elements. If I have array of 11 elements, I want two next standing elements get merged. If I have array of 13 elements, I want three elements merged. And so on. Is there any solution?
Sample #1
var test = ['1','2','3','4','5','6','7','8','9','10','11'];
Need result = [['1'],['2'],['3'],['4'],['5|6'],['7'],['8'],['9'],['10'],['11']]
Sample #2
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13'];
Need result = [['1|2'],['3'],['4'],['5'],['6'],['7|8'],['9'],['10'],['11'],['12|13']]
Thank you in advance.
The following code most probably does what you want.
function condense(a){
var source = a.slice(),
len = a.length,
excessCount = (len - 10) % 10,
step = excessCount - 1 ? Math.floor(10/(excessCount-1)) : 0,
groupSize = Math.floor(len / 10),
template = Array(10).fill()
.map((_,i) => step ? i%step === 0 ? groupSize + 1
: i === 9 ? groupSize + 1
: groupSize
: i === 4 ? groupSize + 1
: groupSize);
return template.map(e => source.splice(0,e)
.reduce((p,c) => p + "|" + c));
}
var test1 = ['1','2','3','4','5','6','7','8','9','10','11'],
test2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21'];
console.log(condense(test1));
console.log(condense(test2));
A - Find the difference and create thus many random numbers for merge and put in array
B - loop through initial numbers array.
B1 - if iterator number is in the merge number array (with indexOf), you merge it with the next one and increase iterator (to skip next one as it is merged and already in results array)
B1 example:
int mergers[] = [2, 7, 10]
//in loop when i=2
if (mergers.indexOf(i)>-1) { //true
String newVal = array[i]+"|"+array[i+1]; //will merge 2 and 3 to "2|3"
i++; //adds 1, so i=3. next loop is with i=4
}
C - put new value in results array
You can try this code
jQuery(document).ready(function(){
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var arrays = [];
var checkLength = test.length;
var getFirstSet = test.slice(0,10);
var getOthers = test.slice(10,checkLength);
$.each( getFirstSet, function( key,value ) {
if(key in getOthers){
values = value +'|'+ getOthers[key];
arrays.push(values);
}else{
arrays.push(value);
}
});
console.log(arrays);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

What does this function do reacjs

This code is come from FB ReactNative Movies Demo
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
what is means ": string" , is return a string ?
This syntax is for the flow type checker. In the argument list you have (score: number) which means the first argument of the function must be a number. After the argument list is the return value of the function. Which is declared as a string.
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
var x: string = getTextFromScore(5);
Flow is pretty smart, though, so we could remove most of these annotations.
// in no situation will this function not return a string
function getTextFromScore(score: number) {
return score > 0 ? score + '%' : 'N/A';
}
// thus, in no situation will x not be a string
var x = getTextFromScore(5);
I like to type the arguments and return value of a function, but usually not the variables unless I think it adds something, either technically or for readability.
It means the function returns a string.
Yes this means this method will return a string value..
if score is greater then 0 return value by concatenating % with it or return 'NA' when value is less then or equal to 0
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
function takes score of type number and returns a string
then
if(score > 0 ){score + '%' }else{'N/A'}

Resources