Skip to content

Instantly share code, notes, and snippets.

@Cologler
Created September 8, 2017 06:17
Show Gist options
  • Save Cologler/84b2ff5d4b08fd9c8dfb58f8b7673202 to your computer and use it in GitHub Desktop.
Save Cologler/84b2ff5d4b08fd9c8dfb58f8b7673202 to your computer and use it in GitHub Desktop.
#javascript_lib
/**
* Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com>
* @param {any} root
* @param {any} options
* */
function sortChildren(root, options) {
options = Object.assign({
filter: () => true,
selector: z => z,
comparer: (x, y) => x - y
}, options || {});
let items = [];
for (var i = 0; i < root.childNodes.length; i++) {
var item = root.childNodes[i];
if (options.filter(item)) {
items.push({
nodeIndex: i,
node: item
});
}
}
items = items.map((z, i) => {
return {
itemIndex: i,
nodeIndex: z.nodeIndex,
node: z.node
};
});
if (items.length > 0) {
const sortedItems = items.slice();
sortedItems.sort((x, y) => {
return options.comparer(
options.selector(x.node),
options.selector(y.node)
);
});
sortedItems.reverse();
sortedItems.forEach((z, i) => {
const newItemIndex = sortedItems.length - i - 1;
const olditemIndex = z.itemIndex;
if (olditemIndex !== newItemIndex) {
const newNodeIndex = items[newItemIndex].nodeIndex;
const before = root.childNodes[newNodeIndex];
console.assert(before !== undefined);
root.insertBefore(z.node, before);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment