UI for Zipcoin Blue

_formatLimit.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict';
  2. var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
  3. var DATE_TIME_SEPARATOR = /t|\s/i;
  4. var COMPARE_FORMATS = {
  5. date: compareDate,
  6. time: compareTime,
  7. 'date-time': compareDateTime
  8. };
  9. module.exports = function (minMax) {
  10. var keyword = 'format' + minMax;
  11. return function defFunc(ajv) {
  12. defFunc.definition = {
  13. type: 'string',
  14. inline: require('./dotjs/_formatLimit'),
  15. statements: true,
  16. errors: 'full',
  17. metaSchema: {
  18. anyOf: [
  19. { type: 'string' },
  20. {
  21. type: 'object',
  22. required: [ '$data' ],
  23. properties: {
  24. $data: {
  25. type: 'string',
  26. anyOf: [
  27. { format: 'relative-json-pointer' },
  28. { format: 'json-pointer' }
  29. ]
  30. }
  31. },
  32. additionalProperties: false
  33. }
  34. ]
  35. }
  36. };
  37. ajv.addKeyword(keyword, defFunc.definition);
  38. ajv.addKeyword('formatExclusive' + minMax);
  39. extendFormats(ajv);
  40. return ajv;
  41. };
  42. };
  43. function extendFormats(ajv) {
  44. var formats = ajv._formats;
  45. for (var name in COMPARE_FORMATS) {
  46. var format = formats[name];
  47. // the last condition is needed if it's RegExp from another window
  48. if (typeof format != 'object' || format instanceof RegExp || !format.validate)
  49. format = formats[name] = { validate: format };
  50. if (!format.compare)
  51. format.compare = COMPARE_FORMATS[name];
  52. }
  53. }
  54. function compareDate(d1, d2) {
  55. if (!(d1 && d2)) return;
  56. if (d1 > d2) return 1;
  57. if (d1 < d2) return -1;
  58. if (d1 === d2) return 0;
  59. }
  60. function compareTime(t1, t2) {
  61. if (!(t1 && t2)) return;
  62. t1 = t1.match(TIME);
  63. t2 = t2.match(TIME);
  64. if (!(t1 && t2)) return;
  65. t1 = t1[1] + t1[2] + t1[3] + (t1[4]||'');
  66. t2 = t2[1] + t2[2] + t2[3] + (t2[4]||'');
  67. if (t1 > t2) return 1;
  68. if (t1 < t2) return -1;
  69. if (t1 === t2) return 0;
  70. }
  71. function compareDateTime(dt1, dt2) {
  72. if (!(dt1 && dt2)) return;
  73. dt1 = dt1.split(DATE_TIME_SEPARATOR);
  74. dt2 = dt2.split(DATE_TIME_SEPARATOR);
  75. var res = compareDate(dt1[0], dt2[0]);
  76. if (res === undefined) return;
  77. return res || compareTime(dt1[1], dt2[1]);
  78. }