Decorate-sort-undecorate idiom: Difference between revisions

m
m (→‎{{header|Wren}}: Better alignment)
Line 96:
{{out}}
<pre>[ 'a', 'is', 'Code', 'site', 'Rosetta', 'programming', 'chrestomathy' ]</pre>
 
Note that <code>Array.prototype.sort()</code> takes an optional compare function that should return a negative integer, a positive integer or zero, depending on whether <code>a</code> is less than, greater than or equal to <code>b</code>. As is, the above implementation of <code>schwartzian()</code> would fail if <code>keyFn</code> returned a string, for example.
 
We could generalize <code>schwartzian()</code> to fallback to a comparison of the string representation of <code>a</code> and <code>b</code>, if they don't support the subtraction operator, and allow calling functions provide a custom compare function.
 
<syntaxhighlight lang="javascript">
function schwartzian(array, keyFn, compareFn) {
const defaultCompareFn = (a, b) =>
a[1] - b[1] || String(a[1]).localeCompare(String(b[1]));
 
return array
.map((e) => [e, keyFn(e)])
.sort(compareFn || defaultCompareFn)
.map((e) => e[0]);
}
 
const example = [
"Rosetta",
"Code",
"is",
"a",
"programming",
"chrestomathy",
"site",
];
 
console.log(schwartzian(example, (e) => e.length));
 
// keyFn is the string in reverse
console.log(schwartzian(example, (e) => Array.from(e).reverse().join("")));
</syntaxhighlight>
 
{{out}}
<pre>
[ 'a', 'is', 'Code', 'site', 'Rosetta', 'programming', 'chrestomathy' ]
[ 'a', 'Rosetta', 'Code', 'site', 'programming', 'is', 'chrestomathy' ]
</pre>
 
=={{header|jq}}==
147

edits