Re: [whatwg/dom] Add convenient, ergonomic, performant API for sorting siblings (#586)

@josepharhar I strongly support the proposal of a basic reordering primitive, which'll allow people to invent their own sort/etc operations on top of it. That's a great idea, and your description of the behavior sounds ideal.

However, that still leaves the base case ("I want to sort these table rows by the value of some cell" or "I want to sort this list by the value of some attribute") relatively unergonomic to do *without* a library. (At *minimum* it's `el.reorderChildren([...el.childNodes].sort(cmpFn))`, and that involves dipping into the DOM many times during the sort.) I think it's necessary to have a reasonably sugared API for the common case *as well as* the generic mechanism.

Luckily having the base primitive means we don't need to get complicated with the sugar; we can focus on the simplest case and let libraries handle all the in-between. I suggest having a second reordering method (suggested name `sortChildElements()`) that, [as suggested above by Domenic/fantasai](https://github.com/whatwg/dom/issues/586#issuecomment-371688518), takes a key function and sorts by its output, along with an overload that takes a string and sorts by the number-parsed value of the named attribute on the children. (That is, `el.sortChildElements("foo")` is equivalent to `el.sortChildElements(x=>+x.getAttribute("foo")`.) This intentionally skips non-element nodes, for simplicity; they'll be sorted to end as per your suggested semantics for `reorderChildren()`.

So total suggested API:

```webidl
partial interface ParentNode {
  Element reorderChildren(sequence<Node> children);
  Element sortChildElements((DOMString or UnaryElementKeyer) keyFn);
};

callback UnaryElementKeyer = any (Element);
```

(I'm assuming that these return the parent node. They could also return `undefined` to match the similar existing functions, but god that's an annoying argument pattern.)

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/586#issuecomment-1426216012
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/586/1426216012@github.com>

Received on Friday, 10 February 2023 19:01:22 UTC