Monday, June 3, 2024
68
rated 0 times [  71] [ 3]  / answers: 1 / hits: 35696  / 11 Years ago, wed, october 9, 2013, 12:00:00

Question



More out of curiosity, but I was wondering how to refactor an if statement to something cleaner / less brittle. From what I have read, polymorphism could have a use?



In the example I only want to return the first car if color:'red' is true.



Coffeescript



example: () ->
cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
if cars[0].color is 'red'
then cars[0]
else cars[1]


Javascript



  example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
if (cars[0].color === 'red') {
return cars[0];
} else {
return cars[1];
}
}


I understand this question maybe closed or moved due to the ambiguous nature


More From » coffeescript

 Answers
7

? : operator is exactly that, a cleaner if-else



http://msdn.microsoft.com/en-us/library/ty67wk28.aspx



classify = (input < 0) ? negative : positive;


There are also switch statements for larger combinations:



http://www.w3schools.com/js/js_switch.asp



switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}


Polymorphism is an abstract concept, not a way to write a statement. It's the practice of creating a method/function/class/etc where type is at least SOMEWHAT ambiguous. So the same method could return a result if fed, say, an integer for parameter 1, the same as if you were to feed an array into the same parameter.


[#75119] Tuesday, October 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
jaylynbrynnk questions
Thu, Jan 28, 21, 00:00, 3 Years ago
Thu, Dec 24, 20, 00:00, 4 Years ago
Sun, Jun 14, 20, 00:00, 4 Years ago
;