Skip to content

Instantly share code, notes, and snippets.

@rgbkrk
Last active January 24, 2022 22:56
Show Gist options
  • Save rgbkrk/c9f8036af4546fc83829239db5e1ad7e to your computer and use it in GitHub Desktop.
Save rgbkrk/c9f8036af4546fc83829239db5e1ad7e 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