Created
March 19, 2020 02:03
-
-
Save joe-oli/5980bf38a624ba546c0e0931b310e474 to your computer and use it in GitHub Desktop.
Lookup corresponding Description, given a Code
This file contains hidden or 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
/* Usage: | |
node LookupDescByCode | |
You can ommit '.js' | |
Using a constant lookup Structure (either Array or Obj), fetch the Code+Desc, given the Code. | |
*/ | |
const CodeDescArrMap = [ | |
{Code: 'Z101', Desc: "Apples"}, | |
{Code: 'Z201', Desc: "Bananas"}, | |
{Code: 'Z301', Desc: "Oranges"} | |
]; | |
//ALTternative: use Object. | |
const CodeDescObjMap = { | |
Z101 : "Apples", | |
Z201 : "Bananas", | |
Z301 : "Oranges" | |
}; | |
//given say, Z101, return code+Desc. | |
getDescByCode = (code) => { | |
let desc = CodeDescObjMap[code]; //using Array-syntax to retrieve .PropVal by .Prop | |
if (desc) //truthy, if found (else undefined) | |
return code + ' - ' + desc; | |
else | |
return code; //just the input code | |
} | |
getDescByCodeALT = (code) => { | |
let foundItem = CodeDescArrMap.filter( function (item, idx) { | |
return item.Code === code; //add item to NEW ARRAY if it satisfies criteria; i.e. *** LHS foundItem is AN ARRAY !!! | |
}); | |
//note 1)if NOT found, LHS is empty array; 2)empty-array [] and empty-object {} are truthy.. WTF? | |
if (foundItem.length) //non-zero is truthy, you dont have to explicitly check for .length > 0 | |
return code + ' - ' + foundItem[0].Desc; | |
else | |
return code; //just the input code | |
} | |
let rtnVal = getDescByCode('Z101'); | |
console.log(rtnVal); | |
let rtnVal2 = getDescByCodeALT('Z201'); | |
console.warn(rtnVal2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment