From 9992fca8814cb56588e694c72ea050e9875095c1 Mon Sep 17 00:00:00 2001 From: Bradley Meck Farias Date: Sat, 11 Nov 2023 14:31:57 -0600 Subject: [PATCH] optimize enums with a single value --- benchmark/bench.js | 24 ++++++++++++++++++++++++ index.js | 29 +++++++++++++++++++++++++++++ test/enum.test.js | 17 +++++++++++++++++ 3 files changed, 70 insertions(+) diff --git a/benchmark/bench.js b/benchmark/bench.js index 12726184..bde02873 100644 --- a/benchmark/bench.js +++ b/benchmark/bench.js @@ -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: { diff --git a/index.js b/index.js index 5958c934..e6d502a9 100644 --- a/index.js +++ b/index.js @@ -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 @@ -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 { diff --git a/test/enum.test.js b/test/enum.test.js index ab861686..1b543b92 100644 --- a/test/enum.test.js +++ b/test/enum.test.js @@ -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({