Feature Flag Evaluate With Rules
Evaluate feature flags with user segment rules percentage rollout and dependency checks for safe progressive delivery.
Code
export function featureFlag(flags){function evaluate(name,context={}){const flag=flags[name];if(!flag||!flag.enabled)return false;if(flag.dependencies)for(const dep of flag.dependencies)if(!evaluate(dep,context))return false;if(flag.segments)for(const seg of flag.segments)if(matchSegment(seg,context))return true;if(flag.percentage!==undefined){const hash=simpleHash(context.userId??'anonymous');return hash%100<flag.percentage;}return flag.enabled;}function matchSegment(seg,ctx){for(const[k,v]of Object.entries(seg))if(Array.isArray(v)?!v.includes(ctx[k]):ctx[k]!==v)return false;return true;}return{evaluate};}function simpleHash(s){let h=0;for(const c of s)h=((h<<5)-h+c.charCodeAt(0))|0;return Math.abs(h);}Report a problem with this exampleOpens a pre-filled issue on GitHub.