Skip to content

Instantly share code, notes, and snippets.

@ivanhoe011
Forked from rgbkrk/sql-mixin.md
Created November 4, 2016 08:03
Show Gist options
  • Save ivanhoe011/d11c7658c92f18ab58d0c61cb5cb16e6 to your computer and use it in GitHub Desktop.
Save ivanhoe011/d11c7658c92f18ab58d0c61cb5cb16e6 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