scoreCalculator.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var Q = require('q');
  2. var debug = require('debug')('ylt:scoreCalculator');
  3. var ScoreCalculator = function() {
  4. 'use strict';
  5. this.calculate = function(data, profile) {
  6. var results = {
  7. categories: {}
  8. };
  9. var weight;
  10. var categoryName;
  11. debug('Starting calculating scores');
  12. // Calculate categories
  13. for (categoryName in profile.categories) {
  14. var categoryResult = {
  15. label: profile.categories[categoryName].label
  16. };
  17. var sum = 0;
  18. var totalWeight = 0;
  19. var rules = [];
  20. for (var policyName in profile.categories[categoryName].policies) {
  21. weight = profile.categories[categoryName].policies[policyName];
  22. if (data.rules[policyName]) {
  23. var policyScore = data.rules[policyName].score + data.rules[policyName].abnormalityScore;
  24. sum += policyScore * weight;
  25. } else {
  26. // Max value if rule is not here
  27. sum += 100 * weight;
  28. debug('Warning: could not find rule %s', policyName);
  29. }
  30. totalWeight += weight;
  31. rules.push(policyName);
  32. }
  33. if (totalWeight === 0) {
  34. categoryResult.categoryScore = 100;
  35. } else {
  36. categoryResult.categoryScore = Math.round(Math.max(sum, 0) / totalWeight);
  37. }
  38. categoryResult.rules = rules;
  39. results.categories[categoryName] = categoryResult;
  40. }
  41. // Calculate general score
  42. var globalSum = 0;
  43. var globalTotalWeight = 0;
  44. for (categoryName in profile.globalScore) {
  45. weight = profile.globalScore[categoryName];
  46. if (results.categories[categoryName]) {
  47. globalSum += results.categories[categoryName].categoryScore * weight;
  48. } else {
  49. globalSum += 100 * weight;
  50. }
  51. globalTotalWeight += profile.globalScore[categoryName];
  52. }
  53. if (globalTotalWeight === 0) {
  54. results.globalScore = 100;
  55. } else {
  56. results.globalScore = Math.round(globalSum / globalTotalWeight);
  57. }
  58. debug('Score calculation finished:');
  59. debug(results);
  60. return results;
  61. };
  62. };
  63. module.exports = new ScoreCalculator();