Skip to content

Instantly share code, notes, and snippets.

@swashcap
Created April 4, 2016 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashcap/21109bd1c05b3fe9beb3ad5c6fb582c2 to your computer and use it in GitHub Desktop.
Save swashcap/21109bd1c05b3fe9beb3ad5c6fb582c2 to your computer and use it in GitHub Desktop.
Pick ordered values snippet
/**
* Pick ordered values.
*
* @example
* pickOrderedValues(
* ['wat', 'silly'],
* { silly: 100, thing: 200, wat: 300 }
* );
* // => [300, 100]
*
* @param {string[]} order Collection of properties to pick from `values`
* @param {Object} values
* @param {boolean} [strict=false] Throw an error if `values` is missing a
* @returns {Array}
*/
function pickOrderedValues(order, values, strict) {
if (!Array.isArray(order)) {
throw new Error('Expected order to be an array');
}
if (!(values instanceof Object)) {
throw new Error('Expected values to be an object');
}
if (strict) {
const valuesKeys = Object.keys(values);
order.forEach(item => {
if (valueKeys.indexOf(item) === -1) {
throw new Error(`Values missing property ${item}`);
}
});
}
return order.reduce((accumulator, prop) => {
return accumulator.concat(values[prop]);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment