Skip to content

Conversation

@nervecenter
Copy link

@nervecenter nervecenter commented Oct 23, 2025

Adds sortedBy, a convenience proc around sorted. The closure comparable should produce a single comparable value for each element, which will then be used to sort with system.cmp by order. Intended to be a generically typed alternative to sortedByIt to avoid the template. Here's my runnableExamples:

import std/math
import std/sugar
import std/sequtils

type Country = tuple[name: string, gdp: float, area: float]

let countries: seq[Country] = @[
  (name: "USA",     gdp: 30.617, area: 9.148),
  (name: "China",   gdp: 19.399, area: 9.326),
  (name: "Germany", gdp: 5.015,  area: 0.349),
  (name: "Japan",   gdp: 4.281,  area: 0.364),
  (name: "India",   gdp: 4.028,  area: 2.973)
]

assert countries.sortedBy(c => c.gdp, Descending).map(c => c.name) == @["USA",
  "China", "Germany", "Japan", "India"]
assert countries.sortedBy(c => c.area, Descending).map(c => c.name) == @["China",
  "USA", "India", "Japan", "Germany"]
assert countries.sortedBy(c => c.area.pow(2.0), Descending).map(c => c.name) == @["China",
  "USA", "India", "Japan", "Germany"]
assert countries.sortedBy(c => c.name).map(c => c.name) == @["China",
  "Germany", "India", "Japan", "USA"]
assert countries.sortedBy(c => c.name[^1]).map(c => c.name) == @["USA",
  "China", "India", "Japan", "Germany"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant