Created
September 8, 2017 06:17
-
-
Save Cologler/84b2ff5d4b08fd9c8dfb58f8b7673202 to your computer and use it in GitHub Desktop.
#javascript_lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright (c) 2017~2999 - cologler <[email protected]> | |
* @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