Coder Social home page Coder Social logo

enum's Introduction

Hi there πŸ‘‹

  • πŸ”­ I’m helping to maintain the best i18n framework for JavaScript and supporting its awesome community ➑️ i18next πŸ˜‰
  • 🌱 Currently creating tutorials and blog posts for various JavaScript integrations for locize ➑️ https://dev.to/adrai
  • πŸ’¬ Ask me about i18next or locize
  • πŸ“« How to reach me: @adrirai on Twitter
  • πŸ‘― And I also spend my time on various serverless projects, like:
  • πŸ•ΈοΈ And I also other stuff:
    • flowchart.js ➑️ Draws simple SVG flow chart diagrams from textual representation of the diagram. (https://flowchart.js.org)
    • enum ➑️ A javascript module that introduces the Enum Type. It works for Node.js, in the browser and for Deno.
    • and a lot of other things...

adrai's GitHub Stats

⚑ Fun fact: I quit my full-time job to try to be self-employed. It seems to be working so far... 😊

enum's People

Contributors

adrai avatar agutierrezcu avatar antjanus avatar burakcan avatar ctjhoa avatar griest024 avatar jasonkarns avatar rayman avatar stoeffel avatar tootallnate avatar vasumahesh1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

enum's Issues

How to use `enum` with `ffi`?

Hi! I'm working on a project that integrates a shared C library with Node. I'm using the ffi module for this which, in turn, uses the ref library for types. I've seen that @TooTallNate did a PR awhile back to implement the type interface so this could be used with ref. I can't, for the life of me, figure out how to get this to work. Full disclosure: I'm not a C programmer at all.

Here's the enum definition in the C code:

typedef enum {
    DEVICE_UNKNOWN,
    DEVICE_IOS_IPHONE,
    DEVICE_IOS_IPOD,
    DEVICE_IOS_IPAD,
    DEVICE_WINDOWS_PC,
    DEVICE_WINDOWS_PHONE,
    DEVICE_WINDOWS_TABLET,
    DEVICE_MAC
} E_DEVICE_TYPE;

There is a method called SetDeviceType that accepts DEVICE_MAC as it's input parameter. In my Javascript I've done the following:

const deviceTypeEnum = new Enum([
  'DEVICE_UNKNOWN',
  'DEVICE_IOS_IPHONE',
  'DEVICE_IOS_IPOD',
  'DEVICE_IOS_IPAD',
  'DEVICE_WINDOWS_PC',
  'DEVICE_WINDOWS_PHONE',
  'DEVICE_WINDOWS_TABLET',
  'DEVICE_MAC',
], { name: 'E_DEVICE_TYPE' });

I've also tried:

const deviceTypeEnum = new Enum({
  DEVICE_UNKNOWN: 0,
  DEVICE_IOS_IPHONE: 1,
  DEVICE_IOS_IPOD: 2,
  DEVICE_IOS_IPAD: 3,
  DEVICE_WINDOWS_PC: 4,
  DEVICE_WINDOWS_PHONE: 5,
  DEVICE_WINDOWS_TABLET: 6,
  DEVICE_MAC: 7,
}, { name: 'E_DEVICE_TYPE' });

I then call my function (defined on ffi) like so:

this.client.setDeviceType(deviceTypeEnum.DEVICE_MAC);

and also tried:

this.client.setDeviceType(deviceTypeEnum.DEVICE_MAC.value);

On the ffi definition I've tried setting the parameter type as int and uint32. Unfortunately, this doesn't seem to be setting the correct value in the C library. Can anyone see if I'm missing something? It's probably something obvious but I've been bashing my head against this for a couple of days and thought I'd reach out for assistance. Thanks for any help you might be able to provide!

Best way to assert an enum item was passed

Lets say you wanted to take an enum item as a parameter to a function.

What's the best way to assert that what was passed is an enum item. I've done some hacks doing index of with the array of values or something similar, but it seems there should be an easier way to do this.

BigInt

Hi,
I use the version 2.5.0 (I'll update, but I don't now when actually).

This plugin fails if more than 32-33 (I don't remember exactly) items flaggables, because the javascript bitwise OR truncate:
see documentation.

I have created a flaggable enum using the BigInt object, and the plugin crash only in one method:

if(!(e.value!==0&&!(e.value&e.value-1))) { return false; }

Fails because cannot use the minus operator between Number and BigInt.

I have tested using typeof and resolved. When I will update to latest version, if this problem will be present yet I'll create a PL.

Solution:

if((typeof e.value==="number")&&(!(e.value !== 0 && !(e.value & e.value - 1)))) { return false; } else if((typeof e.value==="bigint")&&(!(e.value!==0&&!(e.value&e.value-BigInt(1))))) { return false; }

B.r.
Cristiano Larghi

enum.get() does not return the enum item.

var myEnum = new Enum(['A', 'B', 'C']);
var item = myEnum.get('A | B');
console.log(item); // everything fine

// passing a flaged Item to the method get() returns null !

var itemItem = myEnum.get(item);
console.log(itemItem); // variable is null instead of { key: 'A | B', value: 3 }

is the value static ?

if I define new Enum in some classes

can I access it from another class without send refrence to that's class ?

Feature request: case (in)sensitivity

Would you be receptive to adding case insensitivity as an option?

I'm thinking something along the lines of:

var myEnum = new Enum(['One', 'Two'], { caseSensitive: false }); // caseSensitive defaults to true

myEnum.get('one'); // => myEnum.One
myEnum.get('ONE'); // => myEnum.One
myEnum.Two.is('two'); // => true

I would expect that the canonical casing is taken from the constructor argument. So the property accessor (One and Two above) is only available as defined during instantiation. But the get, is, and has lookup methods would be case insensitive (or sensitive) as defined by the provided option (defaulting to sensitive).

Interested in "ref" type support?

Hey there! I'm not sure if you are aware of ref and its counterpart, node-ffi, but I was checking out this module, and thinking it would be really cool to have this Enum module be a supported "Type" for use in FFI'd C functions! There's already ref-array for C arrays, and ref-struct for C-compatible structs in Buffers. Enum is a natural fit!

Do do this, we'd have to have to add a few properties to the Enum class instance, to make it a compatible "ref type".

If you're interested in this, I can probably whip up a PR pretty quickly! Cheers 🍻

Adding Method to Serialize Enum

Serializing 'enums' doesn't include the keys, just the values.

I get this:
["BRANDS_INSPIRED","CRAFTS","DECOR","ELECTRONICS","FURNITURE","HOME_AUTOMATION","HOME_IMPROVEMENT","OUTDOORS","UPCYCLE","WEDDINGS","MISC"]

When I want this:
[{"key":"BRANDS_INSPIRED","value":"Brands Inspired"},{"key":"CRAFTS","value":"Crafts"},{"key":"DECOR","value":"DΓ©cor"},{"key":"ELECTRONICS","value":"Electronics"},{"key":"FURNITURE","value":"Furniture"},{"key":"HOME_AUTOMATION","value":"Home Automation"},{"key":"HOME_IMPROVEMENT","value":"Home Improvement"},{"key":"OUTDOORS","value":"Outdoors"},{"key":"UPCYCLE","value":"Upcycle"},{"key":"WEDDINGS","value":"Weddings"},{"key":"MISC","value":"Miscellaneous"}]

I added a short method to my local copy to make this a bit quicker since I do this a lot. Is there some better way to go about this?

Thanks,

Added method:

 /**
 * Returns an array of objects with key / value pairs for the elements of the enumeration.
 * @return {Array} Objects with key / value attributes
 */

  Enum.prototype.toTuples = function toTuples() {

        var elements = [];

        this.enums.forEach(function (element) {
            if (element.key) {
                elements.push({ 'key': element.key, 'value': element.value });
            } else {
                elements.push(element.value);
            }
        });

        return elements;

    };  

EnumItem#has returns true falsely.

When EnumItem#has is called with a string, it is checked if EnumItem#key (string) contains the string provided to '.has'. I have reached an issue where one enum is a substring of another, e.g. HELL, HELLO. When the EnumItem contains HELLO, and I attempt to use <EnumItem>.has('HELL"), it will incorrectly return true. Please tell me if this is intended or anything, for now I will just have to rename the enums.

Sorry for any inproper usage of terms in advance, I'm relatively new to this dependency (and enums in general).

Extend Enums before freezing?

Hi,

Possible to Extend an Enum before freezing it?

I have a use case:
I have a global npm module that has a set of Enums and is included in an application which has its own set of enums, can I somehow merge them together?

Also by merging as in the global module's Enum is already instantiated...

I wrote a piece of code that does the job, but It wont be as per the requirements i.e. I haven't take aspects like frozen into account yet.

`valueOf()` should return `this.value`, not `this.key`?

How come valueOf() returns the key, instead of the value? If it was this.value, we'd be able to use JavaScript |, similar to the way the Enum separator syntax works:

var myEnum = new Enum(['A', 'B', 'C']);

myEnum.A | myEnum.B;
// 3

myEnum.get('A | B');
// { key: 'A | B', value: 3 }

myEnum.get('A | B').value;
// 3

Thoughts?

isinstance check?

I'm trying to use this in Vue props. But Vue complains that the Enum is not a constructor / class.

Indeed, if I try do to a MyEnum.ENUM instanceof MyEnum, I will get a TypeError saying that "....._default is not a function".

What would be the proper way of making the instance check?

performance issue

It looks like the code freezing stuff introduced in some recent has a negative impact on performance.
We had to revert to a lighter/older implementation of Enum on our project

https://github.com/node-opcua/node-opcua/blob/master/lib/misc/enum.js
https://github.com/node-opcua/node-opcua/blob/master/test/misc/test_enum.js

Our test shows a 50x performance increase:

  Test Enum
    √ should create flaggable enum from string array
    √ should create flaggable enum from flaggable map
    √ should create non-flaggable enum from non-flaggable map
    √ should access enum from enum item name
    √ EnumItem should function properly

  Benchmarking Enums
 CYCLE slowEnum op/s 1251.3981929889926
 CYCLE fastEnum op/s 137125.85574360698
 Fastest is fastEnum
 Speed Up : x 109
    √ should verify that our enums are faster than old enums (1084ms)
 CYCLE slowEnum op/s 624.8278866171509
 CYCLE fastEnum op/s 38325.48636183134
 Fastest is fastEnum
 Speed Up : x 61
    √ should verify that our enums are faster than old enums (1027ms)
 CYCLE slowEnum op/s 937.1482653018942
 CYCLE fastEnum op/s 75088.35966278995
 Fastest is fastEnum
 Speed Up : x 80
    √ should verify that our enums are faster than old enums (1046ms)
  8 passing (3s)

see node-opcua/node-opcua#71

myEnum.A == 'A' evaluates to false

In the readme it's suggested that this:

myEnum.A == 'A'

... should evaluate to true but the unit tests omit this case and in practice it evaluates to false.

Most likely a readme issue.

IE Browser support

What's the expected level of IE support? The tests currently fail to load/run in IE8 and 9. The tests run in IE10 but they all fail (when attempting to instantiate an enum):

TypeError: Object doesn't support property or method '__defineGetter__'

Deno usage?

Is it ok to use this in deno, just like this?

import Enum from 'https://cdn.jsdelivr.net/gh/adrai/enum/index.js'

@ry @bartlomieju @piscisaureus can you give some feedback?
I've no experience with deno and neither with TypeScript.

Iterable enums

It would be nice if enums were iterable so I could do for (let day of DAYS) {...}.

How to iterate Enum Object

This is Enum Object

cameraType=new Enum({'HIKVISION':"HikVision", 'DAHUA':"Dahua", "FOSCAM":"Foscam"});
module.exports.cameraType=cameraType

And when we try to iterate

Object.keys(constant.cameraType).forEach(function(element, key, _array) {
console.log("element is ",element);
console.log("Value is ",constant.cameraType.getValue(element));
});

Then it output contain more variable then we intialize

Output is

element is size
Value is undefined
element is indirection
Value is undefined
element is _options
Value is undefined
element is enums
Value is undefined
element is HIKVISION
Value is HikVision
element is DAHUA
Value is Dahua
element is FOSCAM
Value is Foscam
element is isFlaggable
Value is undefined

Question: How can I retrieve an enum member by value?

Say for example I have this enum:

var Members = new Enum({
  A: "a",
  B: "b"
});

I'd like to be able to do something like:

var member = Members.byValue('a');

Did I miss something in the documentation, or is this currently impossible?

How to use 'enum' with switch statement

How would you be able to use an enum object in a switch statement?

I want to do something like:
switch (conversationType) { CONVERSATION_TYPE.SMS: { // do some stuff break; } }

where CONVERSATION_TYPE is
export const CONVERSATION_TYPE = new Enum( { 'SMS': 1, 'Email': 2, 'Live Chat': 3, 'ChatBot': 4, 'Call': 5 }, { name: 'ConversationType', ignoreCase: true });

Failed to import Enum

import Enum from 'enum'
Could not find a declaration file for module 'enum'. '/Users/jerry/opt/test/project/node_modules/enum/cjs/enum.js' implicitly has an 'any' type.
Try npm i --save-dev @types/enum if it exists or add a new declaration (.d.ts) file containing declare module 'enum';

1 import Enum from 'enum'

Why are the "built" enum-X.js files npmignored?

Most libraries distribute their packaged files with npm so that they can be served to the browser from the same source dir as the server's version.

As it is now, I have to use npm install enum and maintain one version for the server and maintain a separate dependency for the browser. This is not browser friendly even though the library should work great between node and the browser.

So essentially, I'm asking to remove: https://github.com/adrai/enum/blob/master/.npmignore#L3

Add bower.json

Please add a bower.json file to be able to use the enum repository repository with bower.io.

Somehting like this:

{
  "name": "enum",
  "main": "index.js",
  "version": "0.2.6",
  "authors": [
    "adrai"
  ],
  "description": "Enum is a javascript module that introduces the Enum Type. It works for node.js and in the browser",
  "moduleType": [
    "amd",
    "node"
  ],
  "keywords": [
    "enum"
  ],
  "license": "MIT",
  "homepage": "https://github.com/adrai/enum"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.