Skip to content

Commit

Permalink
Optimize mappers function to load selective conversion rules for perf…
Browse files Browse the repository at this point in the history
…ormance improvement
  • Loading branch information
sayan404 committed Mar 28, 2024
1 parent 29e0b0e commit 2756d8b
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions bindings/node/builtin.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
// mappers to store all the mappers of all drafts from draft3 to draft7
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 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)
}

exports.drafts = drafts
return loadRequiredRules(fromIndex, toIndex);
};
exports.drafts = drafts

0 comments on commit 2756d8b

Please sign in to comment.