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

Optimization on mappers function in builtin.js #185

Closed
wants to merge 1 commit into from
Closed
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
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
Loading