index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. module.exports = typecast;
  2. /**
  3. * Cast given `val` to `type`
  4. *
  5. * @param {Mixed} val
  6. * @param {String} type
  7. * @api public
  8. */
  9. function typecast(val, type) {
  10. var fn = typecast[type];
  11. if (typeof fn != 'function') throw new Error('cannot cast to ' + type);
  12. return fn(val);
  13. }
  14. /**
  15. * Cast `val` to `String`
  16. *
  17. * @param {Mixed} val
  18. * @api public
  19. */
  20. typecast.string = function (val) {
  21. if (null == val) return '';
  22. return val.toString();
  23. };
  24. /**
  25. * Cast `val` to `Number`
  26. *
  27. * @param {Mixed} val
  28. * @api public
  29. */
  30. typecast.number = function (val) {
  31. var num = parseFloat(val);
  32. return isNaN(num) ? 0 : num;
  33. };
  34. /**
  35. * Cast `val` to a`Date`
  36. *
  37. * @param {Mixed} val
  38. * @api public
  39. */
  40. typecast.date = function (val) {
  41. var date = new Date(val);
  42. return isNaN(date.valueOf()) ? new Date(0) : date;
  43. };
  44. /**
  45. * Cast `val` to `Array`
  46. *
  47. * @param {Mixed} val
  48. * @api public
  49. */
  50. typecast.array = function (val) {
  51. if (val == null) return [];
  52. if (val instanceof Array) return val;
  53. if (typeof val != 'string') return [val];
  54. var arr = val.split(',');
  55. for (var i = 0; i < arr.length; i++) {
  56. arr[i] = arr[i].trim();
  57. }
  58. return arr;
  59. };
  60. /**
  61. * Cast `val` to `Boolean`
  62. *
  63. * @param {Mixed} val
  64. * @api public
  65. */
  66. typecast.boolean = function (val) {
  67. return !!val && val !== 'false' && val !== '0';
  68. };