Last active
June 17, 2017 14:28
-
-
Save marcoturi/a061a5ae7ac60f82977a07d7879f8729 to your computer and use it in GitHub Desktop.
Feature Toogle model generator
This file contains 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
import { forEach } from 'lodash'; | |
/** | |
* @author Marco Turi <marco.turi@hotmail.it> | |
* @author Stefano Tedeschi <stefano.tedeschi@protechstudio.it> | |
* This function generates an object composed by N elements (states). | |
* Every element is a boolean and only one of them could be true. | |
* This is usefull if you want to implement for example a TAB menager | |
* where the user can active only one tab/page/component. | |
* @example | |
* const tab = generateToggleModel(['home', 'contacts']); | |
* tab.home = true; // now tab.contacts is false | |
* tab.contacts = true; // now tab.home is false | |
* tab.currentStateKey(); // -> contacts | |
* @param states | |
* @returns {...states: boolean} | |
*/ | |
export const generateToggleModel = (states: Array<string>) => { | |
const result: any = {}; | |
result.currentStateKey = () => { | |
let trueKey = ''; | |
forEach(result, (value, key) => { | |
if (key !== 'currentStateKey' && value === true) { | |
trueKey = key; | |
} | |
}); | |
trueKey = trueKey.substr(1); | |
return trueKey; | |
}; | |
states.forEach(state => { | |
const privateM = '_' + state; | |
result[privateM] = false; | |
Object.defineProperty(result, state, { | |
get: () => { | |
return result[privateM]; | |
}, | |
set: (val) => { | |
forEach(result, (localState, key) => { | |
if (key[0] === '_') { | |
result[key] = false; | |
} | |
}); | |
result[privateM] = true; | |
}, | |
}); | |
}); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment