mediumJS ES6+#111

Ordenar emociones (sort emoticons)

Prompt

Sort an array of emotion emoticons in ascending (happy first) or descending (sad first) order. Order: :D (happiest), :), :|, :(, T_T (saddest). Do not mutate the input array.

Solution

function sortEmotions(emotions, order) {
  const rank = { ':D': 0, ':)': 1, ':|': 2, ':(': 3, 'T_T': 4 }
  return [...emotions].sort((a, b) => order === 'asc' ? rank[a] - rank[b] : rank[b] - rank[a])
}
Mentor's take

This is sorting by custom key — the pattern for any domain where order isn't alphabetical or numeric: priority levels, T-shirt sizes, status pipelines. The move is a rank lookup table mapping each value to a number, then a comparator that subtracts ranks. Direction flips by swapping the operands: rank[a] - rank[b] ascending, rank[b] - rank[a] descending — no second sort, no .reverse() needed.

Complexity is the sort's: O(n log n) time; the naive "for each rank bucket, filter the array" approach is O(n·k) and rebuilds order by scanning per category — workable for 5 ranks, but it hardcodes the categories into control flow instead of data. The lookup table keeps the ordering declarative: add a new emotion, touch one line.

Two JS specifics carry the senior signal:

  • sort mutates. [...emotions].sort(...) copies first. Sorting props or state in place is a real React bug class — mutated props break memoization and re-render assumptions. (ES2023 adds toSorted() for exactly this.)
  • The comparator contract is negative/zero/positive, not boolean. (a, b) => rank[a] > rank[b] returns booleans that coerce to 1/0 — no negative case, so the sort is unstable garbage on some engines.

Red flag: sorting the input in place, or a boolean comparator. Both pass casual testing and fail in production — the exact category of bug this question exists to surface.

Say it: "I map values to ranks in a lookup table and subtract in the comparator — copying first because sort mutates, and flipping operands for direction instead of reversing."