@coorpacademy/progression-engine
Version:
79 lines (66 loc) • 2.61 kB
JavaScript
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import get from 'lodash/fp/get';
import head from 'lodash/fp/head';
import isEqual from 'lodash/fp/isEqual';
import filter from 'lodash/fp/filter';
import sortBy from 'lodash/fp/sortBy';
import checkCondition from './condition-operators';
export const DEFAULT_SOURCE = {
type: 'slide',
ref: ''
};
const isRuleAvailable = source => chapterRule => {
const isSameSource = isEqual(source, chapterRule.source);
const hasSameType = (source && source.type) === chapterRule.source.type;
const isGlobalRule = hasSameType && get('source.ref', chapterRule) === '*';
return isSameSource || isGlobalRule;
};
const isSameType = refValue => value => {
if (Array.isArray(value) && Array.isArray(refValue)) return value.every(isSameType(refValue[0]));
return typeof refValue === typeof value;
};
const matchWithState = state => chapterRule => {
const conditions = chapterRule.conditions;
return conditions.every(condition => {
const { target, operator, values } = condition;
switch (target.scope) {
case 'slide':
{
const { ref, field } = target;
const answerRecord = state.allAnswers.reverse().find(record => {
return record.slideRef === ref;
});
if (!answerRecord) return false;
const value = answerRecord[field];
const typedValues = values.filter(isSameType(value));
return checkCondition(operator, typedValues, value);
}
case 'variable':
{
const { field } = target;
const variables = _extends({
lives: state.lives,
stars: state.stars
}, state.variables);
const value = variables[field];
const typedValues = values.filter(isSameType(value));
return checkCondition(operator, typedValues, value);
}
/* istanbul ignore next */
default:
{
return false;
}
}
});
};
const selectRule = (rules, state) => {
const targetedChapterRules = filter(isRuleAvailable(state ? state.nextContent : DEFAULT_SOURCE), rules);
const sortedChapterRules = sortBy('priority', targetedChapterRules);
if (!state) {
return head(sortedChapterRules);
}
return sortedChapterRules.find(matchWithState(state)) || null;
};
export default selectRule;
//# sourceMappingURL=select-rule.js.map