Skip to content

Commit

Permalink
add support for different types of functions
Browse files Browse the repository at this point in the history
  • Loading branch information
koddsson committed Jan 6, 2024
1 parent e732123 commit 8e2bb74
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import { truncate } from './helpers.js'
import type { Options } from './types.js'

export default function inspectFunction(func: Function, options: Options) {
let functionType = 'Function'
// @ts-ignore
const stringTag = func[Symbol.toStringTag];
if (typeof stringTag === 'string') {
functionType = stringTag;
}

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')
}
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export function inspect(value: unknown, opts: Partial<Options> = {}): string {
if (type === 'object') {
type = toString.call(value).slice(8, -1)
}

// If it is a base value that we already support, then use Loupe's inspector
if (type in baseTypesMap) {
return (baseTypesMap[type as keyof typeof baseTypesMap] as Inspect)(value, options)
Expand Down
30 changes: 30 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]')
})
})

0 comments on commit 8e2bb74

Please sign in to comment.