csharp | test edge.js | list csharp classes | Search

The getNamespacesBySize function parses C# code and retrieves namespaces based on their size, sorting them in descending order. It is exported as a module and takes a string of C# code as input, returning an array of namespace names.

Run example

npm run import -- "list csharp namespaces"

list csharp namespaces


async function getNamespacesBySize(code) {
    const selectCode = await importer.import("select antlr tree")
    const result = await selectCode(['//namespace_declaration', {
      start: './@start',
      stop: './@stop',
      name: '(./qualified_identifier/@strdata)[1]'
    }], code, 'csharp')
    result.sort((a, b) => (b.stop - b.start) - (a.stop - a.start))
    return result.map(r => r.name)
}

module.exports = getNamespacesBySize

What the code could have been:

const { importAntlrTree } = require('./importer'); // assume importer is a custom module

/**
 * Retrieves namespaces by size from C# code using ANTLR tree.
 * 
 * @param {string} code - The C# code to parse.
 * @returns {Promise} An array of namespace names in descending order of namespace size.
 */
async function getNamespacesBySize(code) {
  // TODO: Consider caching ANTLR tree imports for performance
  const antlrTree = await importAntlrTree('select');

  // Extract namespace declarations from the code
  const namespaceDeclarations = antlrTree(['//namespace_declaration'], code, 'csharp');

  // Filter out namespace declarations with empty names
  const namedDeclarations = namespaceDeclarations.filter(decl => decl.name);

  // Sort namespace declarations by size in descending order
  namedDeclarations.sort((a, b) => (b.stop - b.start) - (a.stop - a.start));

  // Return an array of namespace names
  return namedDeclarations.map(decl => decl.name);
}

module.exports = getNamespacesBySize;

Code Breakdown

Function: getNamespacesBySize

Function Flow:

  1. Importing Dependencies: The importer.import function is used to load the 'select antlr tree' module asynchronously.
  2. Parsing Code: The selectCode function, now referencing the loaded module, is called with the following parameters:
  3. Sorting Result: The obtained result is sorted in descending order based on the size of the namespace declarations (stop position - start position).
  4. Returning Namespaces: The sorted result is mapped to extract and return the namespace names.

Exports:

The getNamespacesBySize function is exported as a module.