utils.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const stripBom = require('strip-bom-string');
  3. const typeOf = require('kind-of');
  4. exports.define = function(obj, key, val) {
  5. Reflect.defineProperty(obj, key, {
  6. enumerable: false,
  7. configurable: true,
  8. writable: true,
  9. value: val
  10. });
  11. };
  12. /**
  13. * Returns true if `val` is a buffer
  14. */
  15. exports.isBuffer = val => typeOf(val) === 'buffer';
  16. /**
  17. * Returns true if `val` is an object
  18. */
  19. exports.isObject = val => typeOf(val) === 'object';
  20. /**
  21. * Cast `input` to a buffer
  22. */
  23. exports.toBuffer = function(input) {
  24. return typeof input === 'string' ? Buffer.from(input) : input;
  25. };
  26. /**
  27. * Cast `val` to a string.
  28. */
  29. exports.toString = function(input) {
  30. if (exports.isBuffer(input)) return stripBom(String(input));
  31. if (typeof input !== 'string') {
  32. throw new TypeError('expected input to be a string or buffer');
  33. }
  34. return stripBom(input);
  35. };
  36. /**
  37. * Cast `val` to an array.
  38. */
  39. exports.arrayify = function(val) {
  40. return val ? (Array.isArray(val) ? val : [val]) : [];
  41. };
  42. /**
  43. * Returns true if `str` starts with `substr`.
  44. */
  45. exports.startsWith = function(str, substr, len) {
  46. if (typeof len !== 'number') len = substr.length;
  47. return str.slice(0, len) === substr;
  48. };