I've written a function that takes a number and returns a value depending on where that number lies on a pre-defined scale. That's probably a little confusing so I've put the code below and added a JSFiddle (although you might be better off in the dev console).
var getSize = function(number){
var sizes = {
100 : 'url_t',
240 : 'url_s',
320 : 'url_n',
500 : 'url_m',
640 : 'url_z',
800 : 'url_c',
1024 : 'url_l',
},
result = sizes[100];
for (var size in sizes){
if(number < size){
result = sizes[size];
break;
}
result = sizes[1024];
}
return result;
};
getSize(10) // returns url_t
getSize(130) // returns url_s
getSize(2000) // returns url_l
getSize(600) // returns url_z
It works and it's fairly performant, it's just a bit icky. I've tried to come up with a better solution but it just feels ickier. Is there anything I'm missing that would make this a bit nicer? I was playing about with putting the sizes in an array so they're a little more JSON-ish, but then I got lost.
for in
to be always properly sorted. \$\endgroup\$ – njzk2 Jul 22 '14 at 20:21