trc-client-core
Version:
The core of the TRC Client
68 lines (58 loc) • 2.31 kB
JavaScript
import Expression, {OperationOrderMap} from 'trc-client-core/src/utils/Expression';
import {COURSE_COMPLETED, COURSE_ENROLLED} from 'trc-client-core/src/constants/Prerequisite';
import {COMPLETED} from 'trc-client-core/src/constants/CourseStatus';
const INVALID_CHARACTERS = /[-]/;
function getValue(obj) {
switch(obj.type) {
case 'Literal':
return obj.value;
default:
return obj.name;
}
}
function recurseToPrerequisite(branch) {
// recurse if there are more prequisites to determine
if (branch.left && branch.right) {
return {
type: branch.operator.toUpperCase(),
prerequisite1: recurseToPrerequisite(branch.left),
prerequisite2: recurseToPrerequisite(branch.right)
}
} else {
if (branch.type === 'MemberExpression') {
return {
type: COURSE_ENROLLED,
courseCode: getValue(branch.object)
}
} else {
return {
type: COURSE_COMPLETED,
courseCode: getValue(branch)
}
}
}
}
function recurseToString(branch, upperBanchValue) {
var {type, prerequisite1, prerequisite2, courseCode, currentStatus} = branch;
const branchValue = OperationOrderMap[type];
// recurse if there are more prequisites to determine
if (prerequisite1 && prerequisite2) {
const binaryOperation = `${recurseToString(prerequisite1, branchValue)} ${type} ${recurseToString(prerequisite2, branchValue)}`;
// Because expression objects are nested in reverse order
// if the upper banch has a higher OperationOrder number it means that
// the original string used brackets to change the order of operations;
return (upperBanchValue > branchValue) ? `(${binaryOperation})` : binaryOperation;
} else {
courseCode = (courseCode.match(INVALID_CHARACTERS)) ? `'${courseCode}'` : courseCode;
return `${courseCode}${(type !== COURSE_COMPLETED) ? '.' + type.replace('COURSE_', '') : ''}`;
}
}
export function parsePrerequisite(str) {
return recurseToPrerequisite(Expression(str));
}
export function stringifyPrerequisite(obj) {
if(obj.type === "NONE"){
return null
}
return recurseToString(obj);
}