CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-polkadot--util

A collection of useful utilities for @polkadot ecosystem with type checking, data conversion, and performance optimization functions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

strings.mddocs/

String Processing

String manipulation utilities including case conversion, formatting, shortening, and encoding/decoding operations for text processing in JavaScript/TypeScript applications.

Capabilities

Case Conversion

Functions for converting string case formats commonly used in programming.

/**
 * Converts string to camelCase format
 * @param value - String to convert (supports kebab-case, snake_case, PascalCase)
 */
function stringCamelCase(value: string): string;

/**
 * Converts string to PascalCase format  
 * @param value - String to convert
 */
function stringPascalCase(value: string): string;

/**
 * Converts first character to lowercase
 * @param value - String to modify
 */
function stringLowerFirst(value: string): string;

/**
 * Converts first character to uppercase
 * @param value - String to modify
 */
function stringUpperFirst(value: string): string;

String Formatting

Utilities for formatting and shortening strings for display purposes.

/**
 * Shortens string with ellipsis for display
 * @param value - String to shorten
 * @param prefixLength - Number of characters to keep at start (default: 6)
 * @param suffixLength - Number of characters to keep at end (default: 6)
 */
function stringShorten(value: string, prefixLength?: number, suffixLength?: number): string;

String Encoding

Functions for converting strings to binary data formats.

/**
 * Converts UTF-8 string to hex string
 * @param value - String to convert to hex
 */
function stringToHex(value: string): HexString;

/**
 * Converts UTF-8 string to Uint8Array
 * @param value - String to convert to bytes
 */
function stringToU8a(value: string): Uint8Array;

Usage Examples

Case Conversion:

import { 
  stringCamelCase, stringPascalCase, 
  stringLowerFirst, stringUpperFirst 
} from "@polkadot/util";

// Convert various formats to camelCase
console.log(stringCamelCase("hello-world")); // "helloWorld"
console.log(stringCamelCase("hello_world")); // "helloWorld" 
console.log(stringCamelCase("HelloWorld"));  // "helloWorld"
console.log(stringCamelCase("hello world")); // "helloWorld"

// Convert to PascalCase
console.log(stringPascalCase("hello-world")); // "HelloWorld"
console.log(stringPascalCase("hello_world")); // "HelloWorld"
console.log(stringPascalCase("helloWorld"));  // "HelloWorld"

// First character manipulation
console.log(stringLowerFirst("HelloWorld")); // "helloWorld"
console.log(stringUpperFirst("helloWorld")); // "HelloWorld"
console.log(stringUpperFirst("API_KEY"));    // "API_KEY"

API and Variable Name Conversion:

import { stringCamelCase, stringPascalCase } from "@polkadot/util";

// Converting API response fields
const apiResponse = {
  "user-name": "john_doe",
  "email-address": "john@example.com",
  "account-status": "active"
};

// Convert to camelCase for JavaScript usage
const jsObject = Object.entries(apiResponse).reduce((acc, [key, value]) => {
  acc[stringCamelCase(key)] = value;
  return acc;
}, {} as Record<string, string>);

console.log(jsObject);
// {
//   userName: "john_doe",
//   emailAddress: "john@example.com", 
//   accountStatus: "active"
// }

// Convert database column names to class names
const tableNames = ['user_accounts', 'api_tokens', 'session_data'];
const classNames = tableNames.map(stringPascalCase);
console.log(classNames); // ['UserAccounts', 'ApiTokens', 'SessionData']

String Shortening:

import { stringShorten } from "@polkadot/util";

// Shorten long identifiers
const longHash = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
const short = stringShorten(longHash);
console.log(short); // "0x1234...abcdef" (6 chars + 6 chars)

// Custom prefix/suffix lengths
const address = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY";
const shortAddress = stringShorten(address, 8, 4);
console.log(shortAddress); // "5GrwvaEF...utQY"

// Shorten user names for display
const longUsername = "very_long_username_that_needs_shortening";
const displayName = stringShorten(longUsername, 10, 3);
console.log(displayName); // "very_long_...ing"

Text Encoding:

import { stringToHex, stringToU8a } from "@polkadot/util";

// Convert text to hex for blockchain storage
const message = "Hello, Polkadot!";
const hexEncoded = stringToHex(message);
console.log(hexEncoded); // "0x48656c6c6f2c20506f6c6b61646f7421"

// Convert text to bytes for cryptographic operations
const bytes = stringToU8a(message);
console.log(bytes); // Uint8Array(16) [72, 101, 108, 108, 111, 44, 32, 80, ...]

// Encoding multilingual text
const multilingual = "こんにちは 🌍 Hello";
const multiBytes = stringToU8a(multilingual);
const multiHex = stringToHex(multilingual);
console.log(`Bytes length: ${multiBytes.length}`); // Longer due to UTF-8 encoding
console.log(`Hex: ${multiHex}`);

Form Field Processing:

import { stringCamelCase, stringLowerFirst, stringUpperFirst } from "@polkadot/util";

// Process form field names
function processFormData(formData: Record<string, any>) {
  return Object.entries(formData).reduce((processed, [key, value]) => {
    // Convert field names to camelCase for consistent API
    const normalizedKey = stringCamelCase(key);
    
    // Process string values
    if (typeof value === 'string') {
      // Capitalize names and titles
      if (normalizedKey.includes('name') || normalizedKey.includes('title')) {
        processed[normalizedKey] = stringUpperFirst(value.toLowerCase());
      } else {
        processed[normalizedKey] = value;
      }
    } else {
      processed[normalizedKey] = value;
    }
    
    return processed;
  }, {} as Record<string, any>);
}

const rawForm = {
  "first-name": "JOHN",
  "last_name": "DOE", 
  "email-address": "john.doe@example.com",
  "phone_number": "+1234567890"
};

const processed = processFormData(rawForm);
console.log(processed);
// {
//   firstName: "John",
//   lastName: "Doe",
//   emailAddress: "john.doe@example.com",
//   phoneNumber: "+1234567890"
// }

URL and Path Processing:

import { stringCamelCase, stringShorten } from "@polkadot/util";

// Convert URL paths to JavaScript identifiers
function urlToIdentifier(url: string): string {
  // Extract path segments and convert to camelCase
  const path = url.replace(/^https?:\/\/[^\/]+/, ''); // Remove domain
  const segments = path.split('/').filter(Boolean);
  const identifier = segments.join('-');
  return stringCamelCase(identifier);
}

console.log(urlToIdentifier('/api/user-accounts/123')); // "apiUserAccounts123"
console.log(urlToIdentifier('/admin/system-settings')); // "adminSystemSettings"

// Create display-friendly URLs
function createDisplayUrl(fullUrl: string): string {
  if (fullUrl.length <= 50) return fullUrl;
  
  try {
    const url = new URL(fullUrl);
    const domain = url.hostname;
    const path = url.pathname;
    
    if (path.length > 20) {
      const shortPath = stringShorten(path, 10, 10);
      return `${domain}${shortPath}`;
    }
    
    return stringShorten(fullUrl, 25, 15);
  } catch {
    return stringShorten(fullUrl, 25, 15);
  }
}

Types

type HexString = `0x${string}`;

Install with Tessl CLI

npx tessl i tessl/npm-polkadot--util

docs

arrays.md

big-numbers.md

compact.md

data-conversion.md

formatting.md

index.md

objects.md

strings.md

system.md

type-checking.md

tile.json