|
| 1 | +import {pick} from 'lodash' |
| 2 | + |
| 3 | +function isEmpty(object) { |
| 4 | + for (const key in object) { |
| 5 | + if (object.hasOwnProperty(key)) { |
| 6 | + return false |
| 7 | + } |
| 8 | + } |
| 9 | + return true |
| 10 | +} |
| 11 | + |
| 12 | +function _stringify(value, options, depth) { |
| 13 | + if (depth > options.maxDepth) { |
| 14 | + return '...' |
| 15 | + } |
| 16 | + if (Array.isArray(value)) { |
| 17 | + if (value.length === 0) { |
| 18 | + return '[empty]' |
| 19 | + } |
| 20 | + const capLength = Math.max(value.length - options.maxBreadth) |
| 21 | + const asString = value.slice(0, options.maxBreadth) |
| 22 | + .map((item, index) => _stringify(item, options, depth + 1)) |
| 23 | + .concat(capLength > 0 ? `…+${capLength}` : []) |
| 24 | + .join(', ') |
| 25 | + |
| 26 | + return depth === 0 ? asString : `[${asString}]` |
| 27 | + } |
| 28 | + if (typeof value === 'object' && value !== null) { |
| 29 | + const keys = Object.keys(value) |
| 30 | + .filter(key => !options.ignoreKeys.includes(key) && typeof value[key] !== 'undefined') |
| 31 | + |
| 32 | + if (isEmpty(pick(value, keys))) { |
| 33 | + return '{empty}' |
| 34 | + } |
| 35 | + |
| 36 | + const asString = keys |
| 37 | + .slice(0, options.maxBreadth) |
| 38 | + .map(key => `${key}: ${_stringify(value[key], options, depth + 1)}`) |
| 39 | + .join(', ') |
| 40 | + |
| 41 | + return depth === 0 ? asString : `{${asString}}` |
| 42 | + } |
| 43 | + const asString = String(value) |
| 44 | + return asString === '' ? '""' : asString |
| 45 | +} |
| 46 | + |
| 47 | +export default function stringify(value, options = {}) { |
| 48 | + const opts = { |
| 49 | + maxDepth: 'maxDepth' in options ? options.maxDepth : 2, |
| 50 | + maxBreadth: 'maxBreadth' in options ? options.maxBreadth : 2, |
| 51 | + ignoreKeys: 'ignoreKeys' in options ? options.ignoreKeys : [] |
| 52 | + } |
| 53 | + return _stringify(value, opts, 0) |
| 54 | +} |
0 commit comments