Crimius / Ebay Averager

// ==UserScript==
// @name         Ebay Averager
// @namespace    http://tampermonkey.net/
// @version      0.4
// @description  Averages sold ebay listings to an alert box.
// @author       Shae Rivard
// @match        https://www.ebay.com/sch/*
// @grant        none
// @license      MIT
// @updateURL    https://openuserjs.org/meta/Crimius/Ebay_Averager.meta.js
// @downloadURL  https://openuserjs.org/src/scripts/Crimius/Ebay_Averager.user.js
// ==/UserScript==

// basic rounding function to avoid built-in rounding errors.
function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

(function() {
    'use strict';
    //variables.  Listings is the collection of elements with sold prices in them
    //listing is an individual listing from the listings collection.
    //average is our running total and final output
    //sp1 and sp2 are Slice Points 1 and 2
    //offers is the count of listings that are offers, thus not factored into our average
    var listings = document.getElementsByClassName("POSITIVE");
    if(listings.length==0){
        listings = document.getElementsByClassName("bidsold");
    }
    var listing = '';
    var average = 0;
    var sp1 = 0;
    var sp2 = 0;
    var offers = 0;
    //Begin looping through listings, parsing out prices, and adding them to average.
    for( var i = 0; i <= listings.length -1; i++) {
        listing = listings[i];
        if(!(listing.classList.contains('STRIKETHROUGH')||listing.classList.contains('DEFAULT'))){
            listing = listing.innerHTML;
            //We check for these characters, specifically because every listing will have a $
            // and some listings will follow their pricing with more elements, so we check for < as well.
            sp1 = listing.indexOf('$');
            sp2 = listing.indexOf('<');
            // we get -1 if the element doesn't exist, so we reset sp2 in those cases.
            if(sp2 == -1){
                sp2 = listing.length;
            }
            // This if counts the offers (strikethrough listings).
            // We only count them, the slice in the next section blanks them and they don't contribute to the total kept in average.
            // We count them so we can subtract the number of offers from i, our count of listings as well as our iteration variable for the loop.
            if(sp1 > sp2){
                offers++;
            }
            //trim the $ and any trailing HTML
            listing = listing.slice(sp1 + 1, sp2);
            average += 1 * listing;
            console.log('Listing Price: ' + listing);
        }
    }
    console.log('Total: ' + average);
    console.log('Count: ' + (i - offers));
    average = round(average / (i - offers), 2);
    console.log('Average: $' + average);
    alert('Average price: $' + average);
})();