Translating Java's `Character.isJavaIdentifierStart` into JavaScript/TypeScript

Currently, I am in the process of transitioning an ANTLR4 grammar from java to typescript.

There are certain parts of the grammar that rely on java-specific features:

JavaLetter
    :   [a-zA-Z$_] // these are the "java letters" below 0xFF
    |   // covers all characters above 0xFF which are not a surrogate
        ~[\u0000-\u00FF\uD800-\uDBFF]
        {Character.isJavaIdentifierStart(_input.LA(-1))}?
    ;

I am faced with the task of adapting the Character.isJavaIdentifierStart method to JavaScript/TypeScript.

What would be the most straightforward approach for accomplishing this? After reviewing the source implementation, it seems like creating a direct port could be quite labor-intensive (and potentially legally questionable?).

My current thought is that using a simple regex might offer a similar functionality (albeit possibly at the expense of performance)?

Answer №1

If you wanted to efficiently search for characters, one approach could be to dump the character set and organize it into a searchable data structure like a search tree.

Below is the program that can be used for dumping:

import java.util.*;

// Program to print numeric ranges [LOW,HIGH] for specific characters based on Java conditions.

class CharRangePrinter {

   private static class Range {

      final int low, high;

      public Range(int low, int high) {
         assert(low <= high);
         this.low = low;
         this.high = high;
      }

      public int length() {
         return high - low + 1;
      }

      public String toString() {
         int length = high - low + 1;
         return "[" + low + "," + high + "]";
      }
   }

   // Option handling

   private final static String want_start_str = "--start";
   private final static String want_part_str = "--part";
   private final static String want_nostart_str = "--nostart";

   private final static int indents = 3;
   private final static int width_limit = 78;

   private static void printRanges(List<Range> ranges) {
      StringBuilder buf = new StringBuilder();
      for (int i = 0; i < ranges.size(); i++) {
         if (i > 0) { buf.append(","); }
         String hold = buf.toString();
         Range range = ranges.get(i);
         buf.append(range);
         if (buf.length() + indents > width_limit) {
            outLine(hold);
            buf = new StringBuilder();
            buf.append(range);
         }
      }
      outLine(buf.toString());
   }

   private static void outLine(String x) {
      for (int i = 0; i < indents; i++) { out(" "); }
      out(x);
      out("\n");
   }

   private static void out(String x) {
      System.out.print(x);
   }

   private static enum WantWhat {start, part, nostart};

   private static WantWhat handleArgv(String[] argv) {
      boolean good_argv = true;
      WantWhat want = null;
      if (argv.length != 1) {
         good_argv = false;
      }
      if (good_argv) {   
         String arg = argv[0];
         if (want_start_str.equals(arg)) {
            want = WantWhat.start;   
         }
         if (want_part_str.equals(arg)) {
            want = WantWhat.part;
         }
         if (want_nostart_str.equals(arg)) {
            want = WantWhat.nostart;
         }
         good_argv = (want != null);
      }
      if (!good_argv) {
         System.err.println("Pass " + want_start_str + " to print codepoints for Character.isJavaIdentifierStart()");
         System.err.println("Pass " + want_part_str  + " to print codepoints for Character.isJavaIdentifierPart()");
         System.err.println("Pass " + want_nostart_str  + " to print codepoints that can be 'part' but cannot be 'start'");
         System.exit(1);
      }      
      return want;
   }

   public static void main(String[] argv) {

      WantWhat want = handleArgv(argv); 
      assert(want != null);

      int start = 0;
      int end = -1;

      List<Range> ranges = new LinkedList<Range>();

      for (int i = 0; i < 0xFFFF; i++) {
         boolean is;
         switch (want) {
            case start:
               is = Character.isJavaIdentifierStart(i);
               break;
            case part:
               is = Character.isJavaIdentifierPart(i);
               break;
            case nostart:
               is = Character.isJavaIdentifierPart(i) && !Character.isJavaIdentifierStart(i);
               break;
            default:
               throw new IllegalStateException("Unexpected selection");
         }
         if (is) {
            if (end < 0) {
               start = i;
               end = i;
            }  
            else {
               end = i;
            }
         }
         else {
            if (end < 0) {
              // Do nothing
            }
            else {
               int length = end - start + 1; 
               ranges.add(new Range(start, end)); 
               end = -1;
            }
         }
      }
      printRanges(ranges);
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validate input string for special characters using Java Spring form Validator

I am currently working on building a Java Spring form that can detect the presence of special characters in an input string. My goal is to have a message display if the user inputs a string that contains any special characters. My main inquiry revolves ar ...

What could be the reason for my inability to import styles.css from @rainbow-me/rainbowkit?

Currently, I am in the process of integrating the rainbowkit and wagmi libraries into an existing website that is built using web3. The integration works fine when I comment out the styles import, but unfortunately, it results in a rather unattractive appe ...

Oops! Looks like there was an issue: TypeError - 'app.use() function needs a middleware'

Recently delving into Node Js, I embarked on a learning journey and attempted the following code. However, it seems to be throwing an error that has left me stumped. Despite searching for solutions, I can't seem to pinpoint what's causing the iss ...

Use the npm-search feature to show only the name and description columns in the search results

After running the command npm search packagename, I noticed that the results are shown in 6 columns: name, description, author, date, version, and keywords. Is there a way to customize npm-search so that it only displays the name and description columns? ...

ReactJS: Component not updating after property change causing re-render failure

I've encountered a React problem and I'm having trouble pinpointing the issue. In the code snippet below, I've implemented an accordion component that should show or hide based on the value of a state variable called displayForm. The goal i ...

Discover the complete compilation of CSS class regulations (derived from various stylesheets) along with their currently active properties for the chosen element

Is there a way to retrieve all the matched CSS Selectors for a selected element and access the properties of each active class applied to that element? I have researched methods like using getMatchedCSSRules and checking out However, I am hesitant to use ...

I keep receiving the error message "URI is null" when using catch() with my HTTPS request

I'm currently working on implementing an HTTPS request to retrieve a JSON object from the following URI: "https://api.agify.io/?name=.". My goal is to provide specific criteria for which name I would like to gather information and determine the averag ...

When transmitting a variable from JavaScript to PHP using Ajax, the data appears to be missing

While attempting to pass a simple string variable using an onclick event, I encountered an issue where the request was successful but the response in the console displayed as empty. Additionally, the xvar variable did not come through properly resulting in ...

Having trouble getting jQuery Ajax data to work properly on the same PHP page?

I am working with a file called 22.php where both the form and PHP script are located. Issues: https://i.sstatic.net/3vG5N.jpg https://i.sstatic.net/5KXz6.jpg 1) After submitting, the result is displayed below. However, it duplicates the form. 2) Ente ...

Is there a callback for static getDerivedStateFromProps that needs both the previous props and state?

Just recently upgraded to react native version 0.54.0 which includes alpha 1 of react 16.3, resulting in numerous warnings about the deprecation of componentWillMount and componentWillReceiveProps. There is an animated route component that heavily relies ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

Numeric value along with two characters following the decimal place

Imagine I have this number: 25297710.1088 My goal is to add spaces between the groups of digits and keep only two decimal places, like this: 25 297 710.10 I tried using the following code snippet: $(td).text().reverse().replace(/((?:\d{2})&bso ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Executing a request using jQuery's ajax method to perform a

I'm having trouble with my ajax call. I just want to show the json data from my php file but it's not working. Any assistance would be greatly appreciated. My PHP script (phonecall.php): <?php $con = mysqli_connect('localhost',&ap ...

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

I'm curious as to why I am receiving an empty array as a response when I send a post request to the API

I am experiencing an issue while sending data to an API using a post method. I have structured the data in an object as per the server's requirements, but upon posting the object to the API, I receive a response with a status of 200 and an empty array ...

Utilizing array.filter() to retrieve objects with values containing specified keywords

In my node.js project, I have an array named products that is structured as follows: [ { product_id: 'adidas-training-shoes', title: 'Adidas Training Shoes', description: 'description', brand: 'brand&a ...

Efficient method of triggering an action on a subcomponent in React Redux without the need to pass props down the component tree

Currently in the process of learning how to utilize react, redux, and react-redux with a straightforward requirement. I aim to display something similar to the layout below... -------------------------------- | title 1 |----------| | | descriptio ...

Searching for a way to display just a portion of a rendered HTML page using JavaScript

With the JavaScript code window.print(), it is possible to print the current HTML page. If there is a div in an HTML page (such as a page generated from an ASP.NET MVC view), the aim may be to only print that specific div. Is there any jQuery unobtrusive ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...