repl.it
@derekhubbard/

feature_flags

JavaScript

a simple solution for determining the state of features in a large application.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const W = 'workstation'
const I = 'integration'
const S = 'stage'
const P = 'production'
const A = ['*'] // A selector for any environment.

const ANON_USER = 0
const REPORT_USER = 2
const CONTENT_USER = 3
const ADMIN_USER = 8

const switches = {
  alive : {
    environment: A,
  },
  debugging : {
    environment: [W, S, I, P],
    minRole : ADMIN_USER,
  },
  easterEgg : null,
  moduleA : {
    environment: [W, S, I],
    minRole : CONTENT_USER,
  },
}

const reduceFlags = (flags, switchKeys) => {
  return flags.reduce((acc, flag) => acc && switchKeys.includes(flag), true);
};

const isSwitchConfiguredForEnv = (flag, env) => {
  const switchEnv = switches[flag].environment;
  if (switchEnv === A) return true;
  return switchEnv.includes(env);
};

const isSwitchConfiguredForRole = (flag, role) => {
  const switchConfig = switches[flag];
  if (!switchConfig.hasOwnProperty('minRole')) return true;
  return switchConfig.minRole <= role;
};

const lookup = (env, flags, role) => {
  console.log(env, flags, role);
  
  // make sure all flags exist
  const switchKeys = Object.keys(switches);
  const allFlagsExist = reduceFlags(flags, switchKeys);
  if (!allFlagsExist) return allFlagsExist;
  
  // check environment
  const isEnvValid = flags.reduce((acc, flag) => acc && isSwitchConfiguredForEnv(flag, env), true);
  
  // check minimum role
  const isRoleValid = flags.reduce((acc, flag) => acc && isSwitchConfiguredForRole(flag, role), true);
  
  // console.log(allFlagsExist, isEnvValid);
  return allFlagsExist && isEnvValid && isRoleValid;
}

// Example call
console.log(lookup('workstation', ['alive'], ADMIN_USER));

// scenarios for evaluation of flags for modules that don't exist
console.log(lookup('workstation', ['alive', 'moduleB'], ADMIN_USER));
console.log(lookup('workstation', ['moduleB', 'alive'], ADMIN_USER));

// scenarios for evaluation of environments
console.log(lookup('production', ['moduleA'], ADMIN_USER));
console.log(lookup('workstation', ['debugging'], ADMIN_USER));

// console.log(isSwitchConfiguredForRole('alive', ADMIN_USER));
// console.log(isSwitchConfiguredForRole('debugging', ADMIN_USER));
// console.log(isSwitchConfiguredForRole('moduleA', ANON_USER));

console.log(lookup('workstation', ['alive'], ADMIN_USER));
console.log(lookup('workstation', ['debugging'], ADMIN_USER));
console.log(lookup('workstation', ['moduleA'], ANON_USER));
Native Browser JavaScript