Skip to content

Instantly share code, notes, and snippets.

@wandroll
Created December 13, 2017 20:48
Show Gist options
  • Save wandroll/5ff61ac9f1c86cd4c29ea98c89d595f4 to your computer and use it in GitHub Desktop.
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)
/**
* 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