Decorate-sort-undecorate idiom: Difference between revisions

Content added Content deleted
(Add JavaScript)
(Added Wren)
Line 153: Line 153:
<pre>
<pre>
['Rosetta', 'Code', 'is', 'a', 'programming', 'chrestomathy', 'site'] => ['a', 'is', 'Code', 'site', 'Rosetta', 'programming', 'chrestomathy']
['Rosetta', 'Code', 'is', 'a', 'programming', 'chrestomathy', 'site'] => ['a', 'is', 'Code', 'site', 'Rosetta', 'programming', 'chrestomathy']
</pre>

=={{header|Wren}}==
Wren doesn't normally print string lists in "quoted" form though I've added the quotes here to be consistent with the other
solutions.

It's not specified how words of equal length are to be sorted. The standard sort() method used here (quicksort under the hood) is unstable and so the sort order for such words is not guaranteed.
<syntaxhighlight lang="ecmascript">var schwartzian = Fn.new { |a, f|
System.print(a.map { |e| [e, f.call(e)] } // decorate
.toList
.sort { |p, q| p[1] < q[1] } // sort
.map { |p| "\"%(p[0])\"" } // undecorate
.toList)
}

var words = ["Rosetta", "Code", "is", "a", "programming", "chrestomathy", "site"]
var length = Fn.new { |s| s.count }
schwartzian.call(words, length)</syntaxhighlight>

{{out}}
<pre>
["a", "is", "site", "Code", "Rosetta", "programming", "chrestomathy"]
</pre>
</pre>