Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.