instanceof.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. var CONSTRUCTORS = {
  3. Object: Object,
  4. Array: Array,
  5. Function: Function,
  6. Number: Number,
  7. String: String,
  8. Date: Date,
  9. RegExp: RegExp
  10. };
  11. module.exports = function defFunc(ajv) {
  12. /* istanbul ignore else */
  13. if (typeof Buffer != 'undefined')
  14. CONSTRUCTORS.Buffer = Buffer;
  15. defFunc.definition = {
  16. compile: function (schema) {
  17. if (typeof schema == 'string') {
  18. var Constructor = getConstructor(schema);
  19. return function (data) {
  20. return data instanceof Constructor;
  21. };
  22. }
  23. var constructors = schema.map(getConstructor);
  24. return function (data) {
  25. for (var i=0; i<constructors.length; i++)
  26. if (data instanceof constructors[i]) return true;
  27. return false;
  28. };
  29. },
  30. CONSTRUCTORS: CONSTRUCTORS,
  31. metaSchema: {
  32. anyOf: [
  33. { type: 'string' },
  34. {
  35. type: 'array',
  36. items: { type: 'string' }
  37. }
  38. ]
  39. }
  40. };
  41. ajv.addKeyword('instanceof', defFunc.definition);
  42. return ajv;
  43. function getConstructor(c) {
  44. var Constructor = CONSTRUCTORS[c];
  45. if (Constructor) return Constructor;
  46. throw new Error('invalid "instanceof" keyword value ' + c);
  47. }
  48. };