Skip to content

Instantly share code, notes, and snippets.

@jimbol
Last active March 30, 2017 13:20
Show Gist options
  • Save jimbol/817a173eb6b7c3c93419b4aa850b7419 to your computer and use it in GitHub Desktop.
Save jimbol/817a173eb6b7c3c93419b4aa850b7419 to your computer and use it in GitHub Desktop.
A simple feature flag implementation

Feature flags

A simple feature flag implementation

Setup

A hash is provided for the current environment in the application setup.

type Features = { [FLAG_NAME]: Boolean | Function };
const features: Features = (NODE_ENV === 'production') ? productionFeatures : testingFeatures;
export featureFlag = setUpFeatureFlags(features, platform);

Extra arguments passed into setUpFeatureFlags will be passed into functions on the feature hash.

Features is a hash of bools and functions that return bools.

const productionFeatures = {
  FOO_FLAG: true,
  BAR_FLAG: function (platform) {
    return platform === 'WEB';
  }
};

Use

type OnOption = any;
type OffOption = ?any;
export Foo = featureFlag(FOO_FLAG, OnOption, OffOption);

This works with reducers, sagas, components, or anything else. The output can be exported by modules at initilization time or inside modules at run time.

Definition

const setUpFeatureFlags = function (features: Features, ...args) {
  return function featureFlag(flag: string, onOption, offOption) {
    if (typeof features[flag] === 'function') {
      return (features[flag](...args)) ? onOption : offOption;
    }

    return (features[flag]) ? onOption : offOption
  }
}
@akinnee
Copy link

akinnee commented Mar 30, 2017

I would also like to be able to enable/disable individual feature flags without changing the code by setting env vars. So maybe the productionFeatures and testingFeatures objects would just be defaults that can be overridden.

@jimbol
Copy link
Author

jimbol commented Mar 30, 2017

Yea I was thinking we could have production features as the default and testing features as overrides

const features = (isProduction)
  ? productionFeatures
  : { ...productionFeatures, ...testingFeatures };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment