Created
March 28, 2019 15:28
-
-
Save acdha/537660d544b9b83a0018db8fdea656ac to your computer and use it in GitHub Desktop.
Simple ES6 utilities which come up on various projects
This file contains 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
export function emptyNode(node) { | |
while (node.lastChild) { | |
node.lastChild.remove(); | |
} | |
} | |
export function sortChildren(container, sortKeyGenerator) { | |
/* | |
Sort all child nodes in a given container using the provided | |
sortKeyExtractor function to obtain the sort key. The values should be | |
anything which will work with a simple < or > comparison; if you want a | |
reverse sort, multiply by -1 first. | |
*/ | |
// Since we will eventually be mutating the node list we will create an | |
// Array with the full results now: | |
let nodes = [...container.childNodes]; | |
// Build an Array of [nodes array index, sort key] pairs so we can extract | |
// the values once and sort them in place: | |
let sortKeys = Array.from( | |
nodes.map((node, index) => [index, sortKeyGenerator(node)]) | |
); | |
sortKeys | |
.sort(([, a], [, b]) => { | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}) | |
.forEach(([index]) => { | |
let child = nodes[index]; | |
container.appendChild(child); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment