Created
September 28, 2022 18:41
-
-
Save justsml/ad2cfcfdfc26a938b09293c93ac8c950 to your computer and use it in GitHub Desktop.
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
/** | |
* `filteredFlagFactory` supports 3 states of a feature flag: | |
* - True, | |
* - False, | |
* - and restricted by ID(s). | |
* | |
*/ | |
export function filteredFlagFactory( | |
flagValue: string, | |
defaultIdField = 'userId' | |
): (args?: any) => boolean { | |
if (isTruthyString(flagValue)) return () => true; | |
if (flagValue && flagValue.length >= 1) { | |
const idSets = getTokenizedIds(flagValue, defaultIdField); | |
return (args) => { | |
const [lookupField, lookupId] = getHeadKeyValue(args); | |
return idSets[lookupField].includes(lookupId); | |
} | |
} | |
return (args) => false; | |
} | |
function isTruthyString(s: string) { | |
s = `${s}`.toLowerCase() | |
return s === 'true' || s === 'yes' || s === 'on' || s === '1' | |
} | |
function getHeadKeyValue(obj: { [key: string]: number | string }) { | |
const [keyValue] = obj != null ? Object.entries(obj) : []; | |
return keyValue; | |
} | |
const idToken = /^\w*:?\d+$/m; | |
function getTokenizedIds(idList: string, defaultIdField = 'userId') { | |
const ids = `${idList}`.split(','); | |
return ids | |
.filter(id => idToken.test(id)) | |
.reduce((idSet: { [fieldName: string]: Array<number | string> }, currentId: string) => { | |
// Extract ID and any prefix/field label | |
let [prefix, id] = currentId.split(':'); | |
// If no prefix, use the defaultIdField | |
if (!id && prefix) { | |
id = prefix; | |
prefix = defaultIdField; | |
} | |
// Add/append ID to the prefix array in the object to return | |
idSet[prefix] = Array.isArray(idSet[prefix]) ? idSet[prefix] : []; | |
idSet[prefix].push(parseInt(id)); | |
return idSet; | |
}, {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment