From 9b8a6deabcd50adc056a64fb705896194710c5c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Oddsson?= Date: Sun, 7 Jan 2024 00:31:33 +0100 Subject: [PATCH] Add support for different types of functions (#77) add support for different types of functions --- src/function.ts | 10 +++++++--- test/functions.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/function.ts b/src/function.ts index bb06afe..414ab2a 100644 --- a/src/function.ts +++ b/src/function.ts @@ -1,10 +1,14 @@ import { truncate } from './helpers.js' import type { Options } from './types.js' -export default function inspectFunction(func: Function, options: Options) { +type ToStringable = Function & {[Symbol.toStringTag]: string}; + +export default function inspectFunction(func: ToStringable, options: Options) { + const functionType = func[Symbol.toStringTag] || 'Function' + const name = func.name if (!name) { - return options.stylize('[Function]', 'special') + return options.stylize(`[${functionType}]`, 'special') } - return options.stylize(`[Function ${truncate(name, options.truncate - 11)}]`, 'special') + return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special') } diff --git a/test/functions.js b/test/functions.js index 9281ead..9108fdc 100644 --- a/test/functions.js +++ b/test/functions.js @@ -65,3 +65,33 @@ describe('functions', () => { }) }) }) + +describe('async functions', () => { + it('returns the functions name wrapped in `[AsyncFunction ]`', () => { + expect(inspect(async function foo() {})).to.equal('[AsyncFunction foo]') + }) + + it('returns the `[AsyncFunction]` if given anonymous function', () => { + expect(inspect(async function () {})).to.equal('[AsyncFunction]') + }) +}) + +describe('generator functions', () => { + it('returns the functions name wrapped in `[GeneratorFunction ]`', () => { + expect(inspect(function* foo() {})).to.equal('[GeneratorFunction foo]') + }) + + it('returns the `[GeneratorFunction]` if given a generator function', () => { + expect(inspect(function* () {})).to.equal('[GeneratorFunction]') + }) +}) + +describe('async generator functions', () => { + it('returns the functions name wrapped in `[AsyncGeneratorFunction ]`', () => { + expect(inspect(async function* foo() {})).to.equal('[AsyncGeneratorFunction foo]') + }) + + it('returns the `[AsyncGeneratorFunction]` if given a async generator function', () => { + expect(inspect(async function* () {})).to.equal('[AsyncGeneratorFunction]') + }) +})