判断 实参类型 isOfType.类型,输出boolean类型

例:
isOfType.null(null) // true
isOfType.array([]) // true

  1. const isOfType = (() => {
  2. // create a plain object with no prototype
  3. const type = Object.create(null);
  4. // check for null type
  5. type.null = x => x === null;
  6. // check for undefined type
  7. type.undefined = x => x === undefined;
  8. // check for nil type. Either null or undefined
  9. type.nil = x => type.null(x) || type.undefined(x);
  10. // check for strings and string literal type. e.g: 's', "s", `str`, new String()
  11. type.string = x => !type.nil(x) && (typeof x === 'string' || x instanceof String);
  12. // check for number or number literal type. e.g: 12, 30.5, new Number()
  13. type.number = x => !type.nil(x)
  14. && (// NaN & Infinity have typeof "number" and this excludes that
  15. (!isNaN(x) && isFinite(x)
  16. && typeof x === 'number'
  17. ) || x instanceof Number);
  18. // check for boolean or boolean literal type. e.g: true, false, new Boolean()
  19. type.boolean = x => !type.nil(x) && (typeof x === 'boolean' || x instanceof Boolean);
  20. // check for array type
  21. type.array = x => !type.nil(x) && Array.isArray(x);
  22. // check for object or object literal type. e.g: {}, new Object(), Object.create(null)
  23. type.object = x => ({}).toString.call(x) === '[object Object]';
  24. // check for provided type instance
  25. type.type = (x, X) => !type.nil(x) && x instanceof X;
  26. // check for set type
  27. type.set = x => type.type(x, Set);
  28. // check for map type
  29. type.map = x => type.type(x, Map);
  30. // check for date type
  31. type.date = x => type.type(x, Date);
  32. return type;
  33. })()