scoreCalculator.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. sum += data.rules[policyName].score * weight;
  24. } else {
  25. // Max value if rule is not here
  26. sum += 100 * weight;
  27. debug('Warning: could not find rule %s', policyName);
  28. }
  29. totalWeight += weight;
  30. rules.push(policyName);
  31. }
  32. if (totalWeight === 0) {
  33. categoryResult.categoryScore = 100;
  34. } else {
  35. categoryResult.categoryScore = Math.round(sum / totalWeight);
  36. }
  37. categoryResult.rules = rules;
  38. results.categories[categoryName] = categoryResult;
  39. }
  40. // Calculate general score
  41. var globalSum = 0;
  42. var globalTotalWeight = 0;
  43. for (categoryName in profile.globalScore) {
  44. weight = profile.globalScore[categoryName];
  45. if (results.categories[categoryName]) {
  46. globalSum += results.categories[categoryName].categoryScore * weight;
  47. } else {
  48. globalSum += 100 * weight;
  49. }
  50. globalTotalWeight += profile.globalScore[categoryName];
  51. }
  52. if (globalTotalWeight === 0) {
  53. results.globalScore = 100;
  54. } else {
  55. results.globalScore = Math.round(globalSum / globalTotalWeight);
  56. }
  57. debug('Score calculation finished:');
  58. debug(results);
  59. return results;
  60. };
  61. };
  62. module.exports = new ScoreCalculator();