Created
April 4, 2016 00:24
-
-
Save swashcap/21109bd1c05b3fe9beb3ad5c6fb582c2 to your computer and use it in GitHub Desktop.
Pick ordered values snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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