From 419000d5568560b9e625ae8229b31cc90beca4ee Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Wed, 19 Dec 2018 22:08:49 -0500 Subject: [PATCH] Expose deno.inspect (#1378) --- js/console.ts | 23 +++++++++++++++++++++++ js/console_test.ts | 9 ++++++++- js/deno.ts | 1 + 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/js/console.ts b/js/console.ts index 94ba437311..ca08330ebe 100644 --- a/js/console.ts +++ b/js/console.ts @@ -474,3 +474,26 @@ export class Console { this.info(`${label}: ${duration}ms`); }; } + +/** + * inspect() converts input into string that has the same format + * as printed by console.log(...); + */ +export function inspect( + value: any, // tslint:disable-line:no-any + options?: ConsoleOptions +) { + const opts = options || {}; + if (typeof value === "string") { + return value; + } else { + return stringify( + value, + // tslint:disable-next-line:no-any + new Set(), + 0, + // tslint:disable-next-line:triple-equals + opts.depth != undefined ? opts.depth : DEFAULT_MAX_DEPTH + ); + } +} diff --git a/js/console_test.ts b/js/console_test.ts index 2946d36489..b0fb9b5c4d 100644 --- a/js/console_test.ts +++ b/js/console_test.ts @@ -1,6 +1,6 @@ // Copyright 2018 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEqual } from "./test_util.ts"; -import { stringifyArgs } from "./console.ts"; +import { stringifyArgs, inspect } from "./console.ts"; import { Console } from "./console.ts"; import { libdeno } from "./libdeno"; @@ -120,6 +120,8 @@ test(function consoleTestStringifyCircular() { // tslint:disable-next-line:max-line-length "Console { printFunc: [Function], log: [Function], debug: [Function], info: [Function], dir: [Function], warn: [Function], error: [Function], assert: [Function], count: [Function], countReset: [Function], time: [Function], timeLog: [Function], timeEnd: [Function] }" ); + // test inspect is working the same + assertEqual(inspect(nestedObj), nestedObjExpected); }); test(function consoleTestStringifyWithDepth() { @@ -138,6 +140,11 @@ test(function consoleTestStringifyWithDepth() { stringifyArgs([nestedObj], { depth: null }), "{ a: { b: { c: { d: [Object] } } } }" ); + // test inspect is working the same way + assertEqual( + inspect(nestedObj, { depth: 4 }), + "{ a: { b: { c: { d: [Object] } } } }" + ); }); test(function consoleTestCallToStringOnLabel() { diff --git a/js/deno.ts b/js/deno.ts index 869314d2cd..a03e41fe30 100644 --- a/js/deno.ts +++ b/js/deno.ts @@ -52,6 +52,7 @@ export { connect, dial, listen, Listener, Conn } from "./net"; export { metrics } from "./metrics"; export { resources } from "./resources"; export { run, RunOptions, Process, ProcessStatus } from "./process"; +export { inspect } from "./console"; export const args: string[] = []; // Provide the compiler API in an obfuscated way