strapi/packages/core/utils/lib/print-value.js

52 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-11-04 10:54:13 +01:00
'use strict';
// Code copied from the yup library (https://github.com/jquense/yup)
// https://github.com/jquense/yup/blob/2778b88bdacd5260d593c6468793da2e77daf21f/src/util/printValue.ts
2022-08-08 15:50:34 +02:00
const { toString } = Object.prototype;
2021-11-04 10:54:13 +01:00
const errorToString = Error.prototype.toString;
const regExpToString = RegExp.prototype.toString;
const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';
const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
function printNumber(val) {
if (val != +val) return 'NaN';
const isNegativeZero = val === 0 && 1 / val < 0;
2022-08-08 15:50:34 +02:00
return isNegativeZero ? '-0' : `${val}`;
2021-11-04 10:54:13 +01:00
}
function printSimpleValue(val, quoteStrings = false) {
2022-08-08 15:50:34 +02:00
if (val == null || val === true || val === false) return `${val}`;
2021-11-04 10:54:13 +01:00
const typeOf = typeof val;
if (typeOf === 'number') return printNumber(val);
if (typeOf === 'string') return quoteStrings ? `"${val}"` : val;
2022-08-08 15:50:34 +02:00
if (typeOf === 'function') return `[Function ${val.name || 'anonymous'}]`;
2021-11-04 10:54:13 +01:00
if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
const tag = toString.call(val).slice(8, -1);
2022-08-08 23:33:39 +02:00
if (tag === 'Date') return Number.isNaN(val.getTime()) ? `${val}` : val.toISOString(val);
2022-08-08 15:50:34 +02:00
if (tag === 'Error' || val instanceof Error) return `[${errorToString.call(val)}]`;
2021-11-04 10:54:13 +01:00
if (tag === 'RegExp') return regExpToString.call(val);
return null;
}
function printValue(value, quoteStrings) {
2022-08-08 15:50:34 +02:00
const result = printSimpleValue(value, quoteStrings);
2021-11-04 10:54:13 +01:00
if (result !== null) return result;
return JSON.stringify(
value,
2022-08-08 23:33:39 +02:00
function replacer(key, value) {
2022-08-08 15:50:34 +02:00
const result = printSimpleValue(this[key], quoteStrings);
2021-11-04 10:54:13 +01:00
if (result !== null) return result;
return value;
},
2
);
}
module.exports = printValue;