Using Proxy to Mimic Enum in Javascript
Javascript doesn't support enum. The normal way that we use the enum is to either define as string constants:
const HTTP_METHOD_GET = 'get';
const HTTP_METHOD_PUT = 'get';
or
const HTTP_METHOD = {
GET: 'get',
PUT: 'put'
}
Both method is error-prone and not vert elegant. In the first method, HTTP_METHOD_GET
and HTTP_METHOD_PUT
are not very tied together. The second method is a little bit better than the first one and group the related constants together. However, if HTTP_METHOD.DELETE
is used, the undefined
is returned and no error is thrown. It is not easy to debug for this type of error.
In ES6, Proxy
provide the capability of customize access to the property of an object. Proxy can be used to mimic the enum in other language:
enumerize.js
export default (keys) => new Proxy(
keys.reduce((obj, key) => {obj[key] = key; return obj}), {}),
{
get(target, key) {
const result = target[key];
if (!result) {
throw new Error(`${key} is not defined in this enum`);
}
}
}
)
Usage:
import enumerize from 'enumerize';
const HttpMethod = enumerize(['PUT', 'GET', 'DELETE'];
expect(HttpMethod.PUT).toBe('PUT'); // true
HttpMethod.put; // Error, typo;
HttpMethod.UPDATE; // Error, undefined.
Congratulations @raycai! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!