Posted By

kayue on 12/31/10


Tagged


Versions (?)

Return different array value depends on condition


 / Published in: JavaScript
 

  1. var DEST_MAP = {
  2. '1': 'USA',
  3. '110000': 'Indiana',
  4. '230000': 'New York'
  5. };
  6.  
  7. var DEST_MAP_UTF8 = {
  8. '1': 'USA',
  9. '110000': 'Indianapolis',
  10. '230000': 'New York City'
  11. };
  12.  
  13. var doc = document,
  14. EMPTY = '';
  15. var charset = doc.charset || doc['characterSet'] || 'gb2312'; // set default charset to gb2312
  16. var isUTF8 = charset.toLowerCase().indexOf('utf-8') != -1;
  17.  
  18. // bad way
  19. var getDestNameByCode = (function() {
  20. if (isUTF8) {
  21. return function(destCode) {
  22. return DEST_MAP_UTF8[destCode] || EMPTY;
  23. }
  24. }
  25. else {
  26. return function(destCode) {
  27. return DEST_MAP[destCode] || EMPTY;
  28. }
  29. }
  30. })();
  31.  
  32. // good
  33. var getDestNameByCode = isUTF8 ?
  34. function(destCode) { return DEST_MAP_UTF8[destCode] || ""; } :
  35. function(destCode) { return DEST_MAP[destCode] || ""; };
  36.  
  37. // best
  38. var MAP = isUTF8 ? DEST_MAP_UTF8 : DEST_MAP;
  39. function getDestNameByCode(destCode) {
  40. return MAP[destCode] || EMPTY;
  41. }

Report this snippet  

You need to login to post a comment.