From 2314e65a77ce176ab8950ff6b673fb6161640be7 Mon Sep 17 00:00:00 2001 From: Sayan Majumder <95490367+sayan404@users.noreply.github.com> Date: Thu, 28 Mar 2024 19:59:22 +0530 Subject: [PATCH] Optimization on mappers function in builtin.js (#186) Optimize mappers function to load selective conversion rules for performance improvement Signed-off-by: sayan404 --- bindings/node/builtin.js | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/bindings/node/builtin.js b/bindings/node/builtin.js index 22dcc45..406c90a 100644 --- a/bindings/node/builtin.js +++ b/bindings/node/builtin.js @@ -1,26 +1,30 @@ -// mappers to store all the mappers of all drafts from draft3 to draft7 +// mappers to store all the mappers of required drafts in an array. const drafts = ['draft3', 'draft4', 'draft6', 'draft7', '2019-09', '2020-12'] -const mappers = drafts.flatMap((draft, index) => { - const rules = [require(`../../rules/jsonschema-${draft}-to-${draft}.json`)] - if (index + 1 < drafts.length) { - rules.push(require(`../../rules/jsonschema-${draft}-to-${drafts[index + 1]}.json`)) - } - return rules -}) - // indexMapper maps drafts to their index in the mappers array. This is used to find the subarray of mappers to be returned. -const indexMapper = new Map(drafts.map((draft, index) => [draft, index * 2])) - +const indexMapper = new Map(drafts.map((draft, index) => [draft, index])) +const loadRequiredRules = (fromIndex, toIndex) => { + const mappers = [] + for (let index = fromIndex; index <= toIndex; index++) { + const draft = drafts[index] + const rule = require(`../../rules/jsonschema-${draft}-to-${draft}.json`) + mappers.push(rule) + if (index < toIndex) { + const nextDraft = drafts[index + 1] + const nextRule = require(`../../rules/jsonschema-${draft}-to-${nextDraft}.json`) + mappers.push(nextRule) + } + } + return mappers +} exports.builtin = (from, to) => { if (!indexMapper.has(from)) { throw new Error(`Invalid "from": ${from}`) - } else if (!indexMapper.has(to)) { + } + if (!indexMapper.has(to)) { throw new Error(`Invalid "to": ${to}`) } - const fromIndex = indexMapper.get(from) const toIndex = indexMapper.get(to) - return mappers.slice(fromIndex, toIndex + 1) + return loadRequiredRules(fromIndex, toIndex) } - exports.drafts = drafts