strict-field v1.1.5
An utility to strict the query to an object.
Installation
Node
$ yarn add strict-field
Browser
<script src="https://unpkg.com/strict-field@1.1.0/dist/strict-field.min.js"></script>
Usage
const strictField = require('strict-field');
const ACTION = strictField(['MOVE', 'TALK', 'WALK']);
console.log(ACTION('MOVE')); // -> MOVE
console.log(ACTION('TALK')); // -> TALK
console.log(ACTION('SOMETHING')); // call console.error;
you can use Object
as parameter if you want to differentiate between keys and value
const strictField = require('strict-field');
const ACTION = strictField({
MOVE: 'person_move',
TALK: 'person_talk',
WALK: 'person_walk'
});
console.log(ACTION('MOVE')); // -> person_move
console.log(ACTION('TALK')); // -> person_talk
console.log(ACTION('SOMETHING')); // call console.error;
Why?
Sometimes, you need to make constants to be grouped in an Object
(e.g., DAYS
, MONTHS
), especially if you are storing your bunch of constants in a single dedicated constants file. If you are doing this, there will be cases where you are accindentally accessing undefined
value (DAYS.MNDAY
).
It will be problematic if you need to pass your constants into a function that doesn't complaint about undefined
value. But, in the case above, the undefined
is not what you want to pass to the function. The undefined
is caused by the typo.
Actually, we have Proxy in Web API that can handle this problem. But Proxy is not supported in some browsers, especially IE. And according to Babel docs, some features cannot be transpilled or polyfilled due to the ES5 limitations.
Because we have to support all browsers (at least their latest version), this little simple utility is created.
Test
$ yarn test