This is a question in Udacity JS course. I am starting to like Javascript. I feel its a misunderstood language :)
We learned about relational operators and how they can classify the relationship between two values. Your job is to write the function
getRelationship(x,y)
function, which should return a string representing whetherx
is >, < or =y
. For example:var rel = getRelationship(2, 3); console.log(rel); // <
If one or both of the values aren't numbers, your function should output:
"Can't compare relationships because [this value] and [that value] [is]/[are] not [a] number[s]."
where
[this value]
and[that value]
are replaced with the non-numerical values. The sentence should be grammatically correct by outputting either is or are and pluralizing number if necessary.For example:
var rel1 = getRelationship("this", 2); console.log(rel1); // "Can't compare relationships because this is not a number" var rel2 = getRelationship("that"); console.log(rel2) // "Can't compare relationships because that and undefined are not numbers"
Notice in the second example, because the y value was missing, the output said that undefined was not a number.
Here is my stab at the solution.
function getRelationship(x, y) {
var respObj = validateArgAsNumber(x,y);
if (respObj.x && respObj.y && !respObj.isXNaN && !respObj.isYNaN) {
console.log("Both are numbers");
if (x > y) {
return ">";
} else if (x < y) {
return "<";
} else {
return "=";
}
} else {
console.log("Both are NOT numbers");
//console.log(respObj);
if ((!respObj.x && !respObj.y) || (respObj.isXNaN && respObj.isYNaN)){
return "Can't compare relationships because " + x + " and " + y + " are not numbers";
}
if (!respObj.x || respObj.isXNaN) {
return "Can't compare relationships because " + x + " is not a number";
}
if (!respObj.y || respObj.isYNaN) {
return "Can't compare relationships because " + y + " is not a number";
}
}
}
function validateArgAsNumber(a,b) {
var response = {};
response.isXNaN = isNaN(a);
response.isYNaN = isNaN(b);
response.x = typeof(a) == 'number';
response.y = typeof(b) == 'number';
return response;
}
console.log(getRelationship(1,4));
console.log(getRelationship(1,1));
console.log(getRelationship("that",2));
console.log(getRelationship("this"," something else"));
console.log(getRelationship(3));
console.log(getRelationship("hi"));
console.log(getRelationship(NaN, NaN));
console.log(getRelationship(NaN));
console.log(getRelationship(NaN, undefined));