notebook | , get cell extension | authoring header template | Search

The niceName function generates user-friendly filenames for code cells by extracting information from the cell's content and applying formatting rules. This function is designed to create descriptive and consistent filenames for better code organization within a notebook environment.

Run example

npm run import -- "nice name"

nice name

var importer = require('../Core');
var getExtension = importer.import("cell extension")

// get previous markdown and extract name that leads back to the current cell
function niceName(cell) {
    var name = cell.questions[0].replace('?', '')
        .replace(/[^a-z0-9]+|\btest\b/igm, ' ')
        .trim()
        .replace(/\s+/igm, '-')
        + getExtension(cell);
    if(name.toLowerCase().includes('readme')) {
        name = 'readme.md';
    }
    if(name.toLowerCase().includes('package-json')) {
        name = 'package.json';
    }
    if(name.toLowerCase().includes('index')) {
        name = 'index.js';
    }
    
    return name;
}

module.exports = niceName;

What the code could have been:

/**
 * Import required functions from the core module.
 * @module importer
 */
const { importCellExtension } = require('../Core');

/**
 * Get the nice name for a given cell.
 * @param {Object} cell - The cell object containing questions.
 * @returns {string} The nice name for the cell.
 */
function niceName(cell) {
  // Extract the question from the cell and convert it to a nice name
  const name = cell.questions[0]
   .replace('?', '') // Remove the '?' from the question
   .replace(/[^a-z0-9]+|\btest\b/igm,'') // Replace invalid characters with spaces
   .trim() // Trim the string
   .replace(/\s+/igm, '-') // Replace multiple spaces with a single '-'
   .concat(importCellExtension(cell)); // Append the cell extension

  // Special case handling for common file names
  if (name.toLowerCase().includes('readme')) {
    name ='readme.md';
  } else if (name.toLowerCase().includes('package-json')) {
    name = 'package.json';
  } else if (name.toLowerCase().includes('index')) {
    name = 'index.js';
  }

  return name;
}

module.exports = niceName;

This code defines a function called niceName that generates a user-friendly filename for a code cell based on its content and type.

Here's a breakdown:

  1. Dependencies:

  2. niceName Function:

  3. Module Export:

In essence, this code provides a way to generate descriptive and consistent filenames for code cells based on their content, making it easier to organize and manage code within a notebook environment.