
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.
Leave Using Proxy to Mimic Enum in Javascript to:
Read more #js posts
Best Posts From raycai
We have not curated any of raycai's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.