Created
December 13, 2017 20:48
-
-
Save wandroll/5ff61ac9f1c86cd4c29ea98c89d595f4 to your computer and use it in GitHub Desktop.
A generic mapper ( when you need to execute several mappings on dataset based on simple rules)
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
/** | |
* A generic String value mapper | |
* @param {String} value - the value to mapp | |
* @param {Array <{re: Regexp, val: {*}}>} mappings - a list of regexp with their mapped Value | |
* @param {*} defaultValue | |
*/ | |
function genMapper ( value, mappings , defaultValue){ | |
const foundValue = mappings.find(({re, val}) => str.match(re)) | |
return foundValue ? foundValue.value : defaultValue | |
} | |
//// example ///// | |
function completeFruitMapper (incompleteFruit) { | |
const mappings = [{re: /ban/, val: 'banana'}, {re: /co/, val: 'coconut'}, {re: /ap/, val: 'apple'}] | |
const defaultValue = 'peach' | |
return genMapper ( value, mappings , defaultValue) | |
} | |
console.log(completeFruitMapper ('pineapple') // apple |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment