Create a high-performance enum with fields and methods like Java with JavaScript

Java enum

Java enums are very sophisticated and you can create enums with multiple fields and methods as follows.

Java.Color.java


enum Color {
	RED("Red", 255, 0, 0),
	YELLOW("yellow", 255, 255, 0),
	GRAY("gray", 155, 155, 155);
	Color(String name, int r, int g, int b) {
		this.name = name;
		this.r = r;
		this.g = g;
		this.b = b;
	}
	public String name;
	public int r, g, b;
	public String toHexCode() {
		return String.format("#%02x%02x%02x", r, g, b);
	}
}
System.out.println(Color.YELLOW.toHexCode()); // => "#ffff00"
System.out.println(Color.GRAY.name); // => "gray"

Implemented in JavaScript

If you implement this obediently with JavaScript, it will surely look like this.

JavaScript.color.js


var Color = (function() {
  var InnerType = function(name, r, g, b) {
    this.name = name;
    this.r = r;
    this.g = g;
    this.b = b;
  };
  InnerType.prototype.toHexCode = function() {
    return '#' + ('00' + this.r.toString(16)).slice(-2) + ('00' + this.g.toString(16)).slice(-2) + ('00' + this.b.toString(16)).slice(-2);
  };
  return {
    RED : new InnerType('Red', 255, 0, 0),
    YELLOW : new InnerType('yellow', 255, 255, 0),
    GRAY : new InnerType('gray', 155, 155, 155)
  };
})();
console.log(Color.YELLOW.toHexCode()); // => "#ffff00"
console.log(Color.GRAY.name); // => "gray"

It looks good at first glance, but ... In Java, it is natural to use this enum as the key of Map.

Map<Color, Integer> colorNums = new HashMap<>();
colorNums.put(Color.RED, 10);
colorNums.put(Color.YELLOW, 20);
colorNums.put(Color.GRAY, 30);
System.out.println(colorNums.get(Color.RED)); // => "10"
System.out.println(colorNums.get(Color.YELLOW)); // => "20"

In the JavaScript version,

var colorNum = {};
colorNum[Color.RED] = 10;
colorNum[Color.YELLOW] = 20;
colorNum[Color.GRAY] = 30;
console.log(colorNum[Color.RED]); // => "30" !!?
console.log(colorNum[Color.YELLOW]); // => "30" !!?

And it doesn't behave as intended. Since Color.RED, Color.YELLOW, and Color.GRAY are objects, the default toString of the object is called when it becomes the key of the associative array, and all three become "[object Object]". Cause.

Implemented in JavaScript (modified version)

So, if you try to return a unique string for each with toString as follows, it will work as intended.

JavaScript.color_fix.js


var Color = (function() {
  const InnerType = function(name, r, g, b, toStringValue) {
    this.name = name;
    this.r = r;
    this.g = g;
    this.b = b;
    this.toString = function() {
      return toStringValue;
    };
  };
  InnerType.prototype.toHexCode = function() {
    return '#' + ('00' + this.r.toString(16)).slice(-2) + ('00' + this.g.toString(16)).slice(-2) + ('00' + this.b.toString(16)).slice(-2);
  };
  return {
    RED : new InnerType('Red', 255, 0, 0, 'RED'),
    YELLOW : new InnerType('yellow', 255, 255, 0, 'YELLOW'),
    GRAY : new InnerType('gray', 155, 155, 155, 'GRAY')
  };
})();
var colorNum = {};
colorNum[Color.RED] = 10;
colorNum[Color.YELLOW] = 20;
colorNum[Color.GRAY] = 30;
console.log(colorNum[Color.RED]); // => "10"
console.log(colorNum[Color.YELLOW]); // => "20"

I'm happy.

Implemented in JavaScript (ES6 version)

However, it's a little disappointing to specify the character string for toString by myself, so if you can use ES6, it's better to automate it using Symbol ().

JavaScript.color_fix_es6.js


const Color = (() => {
  const InnerType = function(name, r, g, b) {
    this.name = name;
    this.r = r;
    this.g = g;
    this.b = b;
    const sym = Symbol();
    this.toString = () => sym;
  };
  InnerType.prototype.toHexCode = function() {
    return '#' + ('00' + this.r.toString(16)).slice(-2) + ('00' + this.g.toString(16)).slice(-2) + ('00' + this.b.toString(16)).slice(-2);
  };
  return {
    RED : new InnerType('Red', 255, 0, 0),
    YELLOW : new InnerType('yellow', 255, 255, 0),
    GRAY : new InnerType('gray', 155, 155, 155)
  };
})();

Java's enum is the strongest, but the flexibility of JavaScript that can achieve almost the same thing is good.

Recommended Posts

Create a high-performance enum with fields and methods like Java with JavaScript
Socket communication with a web browser using Java and JavaScript ②
Socket communication with a web browser using Java and JavaScript ①
Create a Java and JavaScript team development environment (gradle environment construction)
[Java] Create and apply a slide master
Let's try WebSocket with Java and javascript!
[Java] Create a jar file with both compressed and uncompressed with the jar command
Java and JavaScript
Create a CSR with extended information in Java
Create a simple bulletin board with Java + MySQL
Let's create a timed process with Java Timer! !!
[Java] Create something like a product search API
[Java] Create a collection with only one element
Prepare a scraping environment with Docker and Java
How to access Java Private methods and fields
Create a portfolio app using Java and Spring Boot
I tried to create a shopping site administrator function / screen with Java and Spring
Create a Java (Gradle) project with VS Code and develop it on a Docker container
[Java] Create a filter
[Beginner] Create a competitive game with basic Java knowledge
Quickly implement a singleton with an enum in Java
[Note] Create a java environment from scratch with docker
Create a Java, JavaScript team development environment (problem raising)
Create a JAVA WEB application and try OMC APM
Create a Java (Maven) project with VS Code and develop it on a Docker container
Create a blog with Jekyll and GitHub Pages @ Theme setting
I tried to create a java8 development environment with Chocolatey
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Create a blog with Jekyll and GitHub Pages @ Initial Settings
Create a SlackBot with AWS lambda & API Gateway in Java
Define abstract methods in Java enum and write each behavior
Study Java: Use Timer to create something like a bomb timer
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
[Java] Generics classes and generics methods
Create a java method [Memo] [java11]
[Java] Create a temporary file
Create a playground with Xcode 12
Java methods and method overloads
Java abstract methods and classes
Create a simple web server with the Java standard library com.sun.net.httpserver
I can't create a Java class with a specific name in IntelliJ
Create a JVM for app distribution with JDK9 modules and jlink
[Swift] Create a project with Xcode (ver 12.1) and display "Hello, World!"
Create a flyway jar with maven and docker build (migrate) with docker-maven-plugin
[Java] Let's create a mod for Minecraft 1.16.1 [Add and generate trees]
Memorandum No.2 "Making a search history with ArrayList and HashSet" [Java]
[Java] Let's create a mod for Minecraft 1.14.4 [9. Add and generate trees]
[Java] Let's create a mod for Minecraft 1.14.4 [8. Add and generate ore]
Let's create a parameter polymorphic mechanism with Generic Dao and Hibernate
About Java static and non-static methods
Build a Java project with Gradle
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
[Java] Branch enum with switch statement
Use JDBC with Java and Scala.
Create a Java project using Eclipse
[Java] How to create a folder
Output PDF and TIFF with Java 8
[Java] Reduce if statements with Enum
Studying Java 8 (StaticIF and Default methods)