Flags enums

Jacob Bloom mr.jacob.bloom at gmail.com
Wed Aug 26 20:52:25 UTC 2020


For what it's worth, TypeScript has Enums built-in and I find myself using
string literal types instead:

```typescript
type CollisionType = 'CIRCLE' | 'CUBIC_BEZIER_CURVE' | 'RIGID_BODY';

function handleCollision(type: CollisionType) {
  if (type === 'CIRCLE') {
    // ...
  } else if (type === 'SQUARE') { // Tooling errors on this line
    // ...
  }
}
```

In VSCode (and I assume other IDEs that support TypeScript) you can even do
this in vanilla JS with structured JSDoc comments and the tooling will type
check for you:

```javascript
// @ts-check

/** @typedef {'CIRCLE' | 'CUBIC_BEZIER_CURVE' | 'RIGID_BODY'} CollisionType
*/

/**
 * @param {CollisionType} type
*/
function handleCollision(type) {
  if (type === 'CIRCLE') {
    // ...
  } else if (type === 'SQUARE') { // Tooling errors on this line
    // ...
  }
}
```

As far as I know, comparing strings is nearly as performant in most JS
engines as comparing numbers or objects because they use a method called
"string interning"

On Wed, Aug 26, 2020 at 2:25 PM Matheus Dias de Souza <hydroperhh at gmail.com>
wrote:

>
>
> The com.siteblade.util package contains an approximation of this in
> ECMAScript, with no difference, except the valueOf() method (which returns
> String for working with equality), so it ends up with an additional getter
> ‘number’.
>
>
>
> https://www.npmjs.com/package/com.siteblade.util
>
>
>
> You can use either FlagsEnum or Enum.
>
>
>
> import { Enum } from 'com.siteblade.util';
>
>
>
> const CollisionType = Enum('CollisionType', [
>
>     ['CIRCLE'],
>
>     ['CUBIC_BEZIER_CURVE', [10]],
>
>     ['RIGID_BODY', ['rigidBody', 2]]
>
> ]);
>
>
>
> var type = CollisionType('cubicBezierCurve');
>
> console.log( type == 'cubicBezierCurve' );
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20200826/d14ced17/attachment-0001.html>


More information about the es-discuss mailing list