index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var conversions = require('./conversions');
  2. var route = require('./route');
  3. var convert = {};
  4. var models = Object.keys(conversions);
  5. function wrapRaw(fn) {
  6. var wrappedFn = function (args) {
  7. if (args === undefined || args === null) {
  8. return args;
  9. }
  10. if (arguments.length > 1) {
  11. args = Array.prototype.slice.call(arguments);
  12. }
  13. return fn(args);
  14. };
  15. // preserve .conversion property if there is one
  16. if ('conversion' in fn) {
  17. wrappedFn.conversion = fn.conversion;
  18. }
  19. return wrappedFn;
  20. }
  21. function wrapRounded(fn) {
  22. var wrappedFn = function (args) {
  23. if (args === undefined || args === null) {
  24. return args;
  25. }
  26. if (arguments.length > 1) {
  27. args = Array.prototype.slice.call(arguments);
  28. }
  29. var result = fn(args);
  30. // we're assuming the result is an array here.
  31. // see notice in conversions.js; don't use box types
  32. // in conversion functions.
  33. if (typeof result === 'object') {
  34. for (var len = result.length, i = 0; i < len; i++) {
  35. result[i] = Math.round(result[i]);
  36. }
  37. }
  38. return result;
  39. };
  40. // preserve .conversion property if there is one
  41. if ('conversion' in fn) {
  42. wrappedFn.conversion = fn.conversion;
  43. }
  44. return wrappedFn;
  45. }
  46. models.forEach(function (fromModel) {
  47. convert[fromModel] = {};
  48. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  49. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  50. var routes = route(fromModel);
  51. var routeModels = Object.keys(routes);
  52. routeModels.forEach(function (toModel) {
  53. var fn = routes[toModel];
  54. convert[fromModel][toModel] = wrapRounded(fn);
  55. convert[fromModel][toModel].raw = wrapRaw(fn);
  56. });
  57. });
  58. module.exports = convert;