Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize enums with a single value #663

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions benchmark/bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,30 @@ for (let i = 0; i < SHORT_ARRAY_SIZE; i++) {
}

const benchmarks = [
{
name: 'single enum string',
schema: {
type: 'string',
enum: ['hello world']
},
input: 'hello world'
},
{
name: 'const string',
schema: {
type: 'string',
const: 'hello world'
},
input: 'hello world'
},
{
name: 'const number',
schema: {
type: 'number',
const: 123
},
input: 123
},
{
name: 'short string',
schema: {
Expand Down
29 changes: 29 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,33 @@ function buildConstSerializer (location, input) {
return code
}

function buildSingleEnumSerializer (location, input) {
const schema = location.schema
const type = schema.type

const hasNullType = Array.isArray(type) && type.includes('null')

let code = ''

if (hasNullType) {
code += `
if (${input} === null) {
json += 'null'
} else {
`
}

code += `json += '${JSON.stringify(schema.enum[0]).replace(SINGLE_TICK, "\\'")}'`

if (hasNullType) {
code += `
}
`
}

return code
}

function buildValue (context, location, input) {
let schema = location.schema

Expand Down Expand Up @@ -933,6 +960,8 @@ function buildValue (context, location, input) {

if (schema.const !== undefined) {
code += buildConstSerializer(location, input)
} else if (schema.enum && Array.isArray(schema.enum) && schema.enum.length === 1) {
code += buildSingleEnumSerializer(location, input)
} else if (Array.isArray(type)) {
code += buildMultiTypeSerializer(context, location, input)
} else {
Expand Down
17 changes: 17 additions & 0 deletions test/enum.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@
const test = require('tap').test
const build = require('..')

test('use enum with 1 value', (t) => {
t.plan(1)
const stringify = build({
title: 'Example Schema',
type: 'object',
properties: {
status: {
type: 'string',
enum: ['ok']
}
}
})

const obj = { status: 'ok' }
t.equal('{"status":"ok"}', stringify(obj))
})

test('use enum without type', (t) => {
t.plan(1)
const stringify = build({
Expand Down