MrModest

MovieLens func calculatedRating()

Mar 14th, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function calculateRating(e) {
  2.  
  3.       /*
  4.        * Calculates and returns the rating based on the position of cursor w.r.t the
  5.        * plugin container
  6.        */
  7.  
  8.       var position = $normalGroup.offset(),
  9.           nodeStartX = position.left,
  10.           nodeEndX = nodeStartX + $normalGroup.width();
  11.  
  12.       var maxValue = options.maxValue;
  13.  
  14.       // The x-coordinate(position) of the mouse pointer w.r.t page
  15.       var pageX = e.pageX;
  16.  
  17.       var calculatedRating = 0;
  18.  
  19.       // If the mouse pointer is to the left of the container
  20.       if (pageX < nodeStartX) {
  21.  
  22.         calculatedRating = minValue;
  23.       } else if (pageX > nodeEndX) {
  24.         // If the mouse pointer is right of the container
  25.  
  26.         calculatedRating = maxValue;
  27.       } else {
  28.         // If the mouse pointer is inside the continer
  29.  
  30.         /*
  31.          * The fraction of width covered by the pointer w.r.t to the total width
  32.          * of the container.
  33.          */
  34.         var calcPrcnt = (pageX - nodeStartX) / (nodeEndX - nodeStartX);
  35.  
  36.         if (spacing > 0) {
  37.  
  38.           /*
  39.                   * If there is spacing between stars, take the percentage of width covered
  40.                   * and subtract the percentage of width covered by stars and spacing, to find
  41.                   * how many stars are covered, the number of stars covered is the rating
  42.                   *
  43.                   * TODO: I strongly feel that this logic can be improved!, Please help!
  44.                   */
  45.           calcPrcnt *= 100;
  46.  
  47.           var remPrcnt = calcPrcnt;
  48.  
  49.           while (remPrcnt > 0) {
  50.  
  51.             if (remPrcnt > percentOfStar) {
  52.  
  53.               calculatedRating += step;
  54.               remPrcnt -= percentOfStar + percentOfSpacing;
  55.             } else {
  56.  
  57.               calculatedRating += remPrcnt / percentOfStar * step;
  58.               remPrcnt = 0;
  59.             }
  60.           }
  61.         } else {
  62.  
  63.           /*
  64.            * If there is not spacing between stars, the fraction of width covered per
  65.            * `maxValue` is the rating
  66.            */
  67.           calculatedRating = calcPrcnt * options.maxValue;
  68.         }
  69.  
  70.         // Round the rating if `halfStar` or `fullStar` options are chosen
  71.         calculatedRating = round(calculatedRating);
  72.       }
  73. }
Add Comment
Please, Sign In to add comment