-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.js
75 lines (61 loc) · 1.98 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md.
*/
import { stringify as javascriptStringify } from 'javascript-stringify';
export function stringify( value, quotesAroundText = true ) {
if ( value === undefined ) {
return 'undefined';
}
if ( typeof value === 'function' ) {
return 'function() {…}';
}
const stringified = javascriptStringify( value, stringifySingleToDoubleQuotesReplacer, null, {
// https://github.com/ckeditor/ckeditor5-inspector/issues/98
// https://github.com/ckeditor/ckeditor5-inspector/issues/129
maxDepth: 2
} );
// Note: Remove leading and trailing quotes (") from the output. By default it is:
//
// JSON.stringify( 'foo' ) => '"foo"'
// JSON.stringify( true ) => '"true"'
// JSON.stringify( {} ) => '{}'
// JSON.stringify( [] ) => '[]'
//
// What should be returned:
//
// stringify( 'foo' ) => 'foo'
// stringify( true ) => 'true'
// stringify( {} ) => '{}'
// stringify( [] ) => '[]'
//
if ( !quotesAroundText ) {
return stringified.replace( /(^"|"$)/g, '' );
}
return stringified;
}
export function uid() {
return Math.random().toString( 36 ).substring( 7 );
}
export function stringifyPropertyList( list ) {
const stringified = {};
for ( const name in list ) {
stringified[ name ] = list[ name ];
stringified[ name ].value = stringify( stringified[ name ].value );
}
return stringified;
}
export function truncateString( string, length ) {
if ( string.length > length ) {
return string.substr( 0, length ) + `… [${ string.length - length } characters left]`;
}
return string;
}
// Unlike JSON.stringify(), javascript-stringify returns single quotes around text.
// Retain the JSON.stringify() formatting instead of fixing 100 tests across the project :)
function stringifySingleToDoubleQuotesReplacer( value, indent, stringify ) {
if ( typeof value === 'string' ) {
return `"${ value.replace( '\'', '"' ) }"`;
}
return stringify( value );
}