Skip to content

Instantly share code, notes, and snippets.

@rgbkrk
Last active Oct 12, 2021
Embed
What would you like to do?
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