String
APILightweight namespace for string manipulation
Motivation
globalThis.String functions and methods are very useful but has the following drawbacks :
- Most functions are on the
prototype- Since ESM, it creates a double syntax standard
toDashCase(string)VSmyString.toLowerCase() String.prototypeshould never be extended
- Since ESM, it creates a double syntax standard
- Some legacy design decisions
indexOf,lastIndexOfreturns-1when not found
String namespace corrects these problems in a pragmatic way :
- Extendable : as an object
Stringcan be extends with a simple{ ...String, myMethod() {} } - Uniform : every
Stringfunction has a string as first parameter - Expressive :
indexOfandlastIndexOfreturnsOption<Int>
Usage
import { String, Option, Int } from '@w5s/core';
const baseName = (path: string): Option<string> => {
const positionOption = String.lastIndexOf(path, '/'); // Option<Int>;
const afterLastSlash = Option.map(positionOption, (position) => String.slice(path, position + 1)); // everything after the last slash
return afterLastSlash;
};
Coding Guide
astuce
Prefer String functions over globalThis.String
- At best
Stringwill provide polyfill / better performance / better type safety - At worst
Stringwill call the native function