Skip to content

Instantly share code, notes, and snippets.

@antonioaguilar
Forked from rgbkrk/sql-mixin.md
Created October 12, 2021 11:53
Show Gist options
  • Save antonioaguilar/2d2800d4d4472118b10468e8cbca4e78 to your computer and use it in GitHub Desktop.
Save antonioaguilar/2d2800d4d4472118b10468e8cbca4e78 to your computer and use it in GitHub Desktop.
Turning lodash into declarative SQL

Lodash has a sweet feature called a mixin that lets you alias function names. Below here I alias names that we're used to using in SQL to (roughly) equivalent functions in lodash.

_.mixin({
  select: _.map,
  from: _.chain,
  where: _.filter,
  groupBy: _.sortByOrder,
})

Which allows us to write the JavaScript equivalent of

SELECT p.firstname, p.birthYear FROM Person p
WHERE p.birthYear > 1903 and p.country IS NOT 'US'
GROUP BY p.firstname, p.birthYear

as

_.from(persons)
 .where(p => p.birthYear > 1900 && p.address.country !== 'US')
 .groupBy(['firstname', 'birthYear'])
 .select('firstname', 'birthYear')
 .value() // Lazily evaluated up until this point!

Credit goes to Luis Atencio's Functional Programming in JavaScript book.

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