Skip to content

Commit

Permalink
Optimization on mappers function in builtin.js (#186)
Browse files Browse the repository at this point in the history
Optimize mappers function to load selective conversion rules for performance improvement

Signed-off-by: sayan404 <sayanmajumder0002@gmail.com>
  • Loading branch information
sayan404 committed Mar 28, 2024
1 parent 29e0b0e commit 2314e65
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions bindings/node/builtin.js
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 2314e65

Please sign in to comment.