Steam cart sorter

sort the Steam cart by price

目前為 2018-02-03 提交的版本,檢視 最新版本

// ==UserScript==
// @name                Steam cart sorter
// @name:ZH-CN          Steam 购物车自动排序
// @namespace           http://tampermonkey.net/
// @version             0.3
// @description         sort the Steam cart by price
// @description:ZH-CN   对 Steam 购物车中的物品按照价格排序
// @author              SLAPaper
// @match               http://store.steampowered.com/cart/
// @grant               none
// @license             MIT
// ==/UserScript==

(function() {
    'use strict';

    function sorter(isAsc) {
        let cart_item_list = document.querySelector('.cart_item_list');
        let items = Array.from(cart_item_list.children);

        items.sort((a, b) => {
            let anode = a.querySelector('.price:last-of-type');
            let bnode = b.querySelector('.price:last-of-type');

            if (!anode) {
                return -1;
            }
            if (!bnode) {
                return 1;
            }
            let aval = parseInt(anode.textContent.slice(2));
            let bval = parseInt(bnode.textContent.slice(2));

            if (isAsc) {
                return aval - bval;
            }
            else {
                return bval - aval;
            }
        });

        for (let i = 0; i < items.length; ++i) {
            cart_item_list.appendChild(items[i]);
        }
    }

    let sort_btn = document.createElement('div');
    sort_btn.className = 'SortCart';
    sort_btn.innerHTML = `
        <button class="SortCartAsc">Sort Cart Ascend</button>
        <button class="SortCartDesc">Sort Cart Descent</button>
    `;

    document.querySelector('.rightcol').insertBefore(sort_btn, document.querySelector('.rightcol h2'));

    document.querySelector('.SortCartAsc').addEventListener('click', () => {sorter(true);});
    document.querySelector('.SortCartDesc').addEventListener('click', () => {sorter(false);});
})();