summaryrefslogtreecommitdiff
path: root/shell/lib/util.js
diff options
context:
space:
mode:
Diffstat (limited to 'shell/lib/util.js')
-rw-r--r--shell/lib/util.js35
1 files changed, 35 insertions, 0 deletions
diff --git a/shell/lib/util.js b/shell/lib/util.js
new file mode 100644
index 00000000..6f87dfd7
--- /dev/null
+++ b/shell/lib/util.js
@@ -0,0 +1,35 @@
+export const inspect = arg => {
+ if (arg === null || typeof arg !== 'object') return arg;
+
+ try {
+ return JSON.stringify(arg, undefined, 2);
+ } catch (error) {
+ return '[Circular]';
+ }
+};
+
+const placeholderRegExp = /%[sdo%]/g;
+const placeholderHandlers = {
+ '%s': arg => String(arg),
+ '%d': arg => Number(arg),
+ '%o': arg => inspect(arg),
+};
+
+export const format = (fmt, ...args) => {
+ if (typeof fmt !== 'string') return args.map(inspect).join(' ');
+
+ const str = String(fmt).replace(placeholderRegExp, placeholder => {
+ if (placeholder === '%%') return '%';
+ if (!args.length) return placeholder;
+ const [arg] = args.splice(0, 1);
+ const handler = placeholderHandlers[placeholder];
+ return handler ? handler(arg) : placeholder;
+ });
+
+ return [str, ...args.map(inspect)].join(' ');
+};
+
+export const range = (start, end) => {
+ const size = end - start;
+ return new Array(size).map((v, i) => start + i);
+};