Skip to content

Instantly share code, notes, and snippets.

@jmerrifield
Created September 30, 2015 00:11
Show Gist options
  • Save jmerrifield/f55a1a87a3bce7643fc0 to your computer and use it in GitHub Desktop.
Save jmerrifield/f55a1a87a3bce7643fc0 to your computer and use it in GitHub Desktop.
Lodash of the day: Generating command line args

Creating an array where under some conditions we include extra pairs of values.

Original

var mysqlArgs = ['-h', mysqlConfig.host, '-d', mysqlConfig.database];

if (mysqlConfig.user) {
  mysqlArgs.push('-U', mysqlConfig.user);
}

if (mysqlConfig.password) {
  mysqlArgs.push('-p', mysqlConfig.password);
}

lodash-ified

var mysqlArgs = _({
  '-h': mysqlConfig.host,
  '-d': mysqlConfig.database,
  '-U': mysqlConfig.user,
  '-p': mysqlConfig.password
})
.pick(_.identity) // remove falsey values
.pairs() // turn into an array of ['-key', 'value'] pairs
.flatten() // turn into a single array like ['-key1' 'value1' '-key2' 'value2']
.value();
@koozdra
Copy link

koozdra commented Oct 14, 2015

pick(_.identity) is really slick

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