🪴\zansh.in\js

Play with the controls to see how the code works. All code is present in the page, but some scrollback may be necessary to grok everything.

# array sorting callbacks

2 min read

Create a factory that produces sorting functions you can apply to arrays of numbers or objects.

# mutation

const chars = ['a', '🪴', 'n', 'Z']
const sort = arr => [...arr].sort()
const sortInPlace = arr => arr.sort()

# numbers vs. strings

const numbers = [2, 3, 1, 10]
const strings = ['2', '3', '1', '10']
const sort = arr => [...arr].sort()

# err... numbers?

const numbers = [2, 3, 1, 10]
const sort = () =>
[...numbers].sort()
const sortCompare = () =>
[...numbers].sort(compare)

# compare()

const oneAndTen = compare(1, 10)
const oneAndOne = compare(1, 1)
const tenAndOne = compare(10, 1)
function compare(a, b) {
if (a < b) return -1
if (a === b) return 0
if (a > b) return 1
}

# CompareField()

const objects = [
{ id: 2, name: 'two' },
{ id: 3, name: 'three' },
{ id: 1, name: 'one' }
]
const unsorted = () =>
objects.map(x => x.name)
const sort = () =>
[...objects]
.sort(CompareField('id'))
.map(x => x.name)
function CompareField(field) {
return (a, b) => {
if (a[field] < b[field]) return -1
if (a[field] === b[field]) return 0
if (a[field] > b[field]) return 1
}
}

# sort(By...)

const sortById = () =>
[...objects]
.sort(ByNumber('id'))
.map(x => x.name)
const sortByName = () =>
[...objects]
.sort(ByString('name'))
.map(x => x.name)
function ByNumber(field) {
if (field) {
return (a, b) => +a[field] - +b[field]
} else {
return (a, b) => +a - +b
}
}
function ByString(field) {
if (field) {
return CompareField(field)
} else {
return compare
}
}

# ByNumberReversed()

const sortById = () =>
[...objects]
.sort(ByNumber('id'))
.map(x => x.name)
const sortByIdReversed = () =>
[...objects]
.sort(ByNumberReversed('id'))
.map(x => x.name)
function ByNumberReversed(field) {
return BinarySwap(ByNumber(field))
}
function BinarySwap(fn) {
return (a, b) => fn(b, a)
}

Google it:

🌸 Array map 🌺 Array sort 🌷 Array sort callback 🌻 binary function arity 🌼 high-order function 🌹 mutable 💐 partial application 🌸 spread rest 🌺 type coercion