Skip to content

Instantly share code, notes, and snippets.

@nikcorg
Created July 25, 2013 12:55
Show Gist options
  • Save nikcorg/6079335 to your computer and use it in GitHub Desktop.
Save nikcorg/6079335 to your computer and use it in GitHub Desktop.
Sorting the order history table on david silver spares' website. Custom map/reduce/forEach function because browser natives were overwritten. Just an exercise for fun.
function forEach(a, fn) {
var i;
for (i in a) {
if (a.hasOwnProperty(i)) {
fn.call(null, a[i], i, a);
}
}
}
function map(a, fn) {
var i, r = [];
for (i in a) {
if (a.hasOwnProperty(i)) {
r[r.length] = fn.call(null, a[i], i, a);
}
}
return r;
}
function reduce(a, fn, seed) {
var i;
for (i in a) {
// If seed is omitted, pick the first value of a as the seed
if (typeof(seed) === "undefined") {
seed = a[i];
} else {
if (a.hasOwnProperty(i)) {
seed = fn.call(null, seed, a[i], i, a);
}
}
}
return seed;
}
function sortcmp(a, b) {
return reduce(
map([b, a], function (row) {
return parseInt(row.querySelector("td").innerText, 10);
}),
function (s, v) {
return Math.min(Math.max(-1, s - v), 1);
}
);
}
var container = document.querySelector("#cartcontents");
var rows = [].slice.call(container.querySelectorAll("tr"), 1);
forEach(map(
rows,
function (tr) {
return tr.parentNode.removeChild(tr);
}
).
sort(sortcmp),
function (tr) {
container.appendChild(tr);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment