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