My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
OEnum  
Overview of OEnum
Updated Nov 22, 2010 by matr...@mac.com

OEnum

Creates a new enum class along with the specified instances.

Usage

var MyEnum = OEnum( values );

or

var MyEnum = OEnum( object );

values An argument list of enumerator item names
object A single object argument containing custom values (see below)

Methods

The created instances have some helpful methods to interrogate the enum.

getValue

Gets the value of the item.

getName

Gets the name of the item.

Example

The following code creates an enum class called Sizes:

var Sizes = OEnum("Small", "Medium", "Large");

A new class will be created called Sizes and three static instances will be generated, namely:

Sizes.Small
Sizes.Medium
Sizes.Large

Specifying custom values

To provide custom values (instead of just an increasing index counter) you can pass a single object to OEnum:

var Sizes = OEnum({
  Small: 100,
  Medium: 200,
  Large: 300
});

Sizes.fromValue(100);
// returns Sizes.Small

Sizes.fromValue(200);
// returns Sizes.Medium

Sizes.fromValue(300);
// returns Sizes.Large

Checking the type of an enum value

Each enum value is the type (.kind) of the enum itself. For example, Sizes.Small is of type Sizes, so the following code returns true:

alert( Sizes.Small.kind === Sizes );

Reflecting on an enum

The enum class that gets generated contains a static array called names which allows you to iterate over the acceptable items.

var Sizes = OEnum("Small", "Medium", "Large");

Sizes.names
// returns ["Small", "Medium", "Large"]

The value associated with the name is the position at which it occurs in the array, so Small is 0, Medium is 1 and Large is 2.

Looking up an instance by value

To look up an enum instance by the value, use the static fromValue method:

var Sizes = OEnum("Small", "Medium", "Large");

Sizes.fromValue(0);
// returns Sizes.Small

Sizes.fromValue(1);
// returns Sizes.Medium

Sizes.fromValue(2);
// returns Sizes.Large

Sign in to add a comment
Powered by Google Project Hosting