๐Ÿ‘”String extension

JS โŸฉ value โŸฉ primitive โŸฉ String โŸฉ extension

add custom methods to String.prototype.

// ๐Ÿ”ธ str.characters                - iterable iterator of characters
// ๐Ÿ”ธ str.codePoints                - array of code points
// ๐Ÿ”ธ str.codeUnits                 - array of code units
// ๐Ÿ”น str.replaceWhitespaces()
// โญ install "grapheme-splitter": `npm install grapheme-splitter`

// 2023.01.03 - 19:40 + .codeUnits, .codePoints (support `GraphemeSplitter`)
//
// โญ  String extension
// -------------------------------------------------------------------
// ๐Ÿ”ธ str.characters                - iterable iterator of characters
// ๐Ÿ”ธ str.codePoints                - array of code points
// ๐Ÿ”ธ str.codeUnits                 - array of code units
// ๐Ÿ”น str.replaceWhitespaces()
// -------------------------------------------------------------------

const { range } = require('./Iterable.js');      // iterable methods

// โญ import 'grapheme-splitter'
const GraphemeSplitter = require('grapheme-splitter');
const splitter = new GraphemeSplitter();
// -------------------------------------------------------------------

// String extension
Object.defineProperties(String.prototype, {

    // ๐Ÿ”น str.replaceWhitespaces()
    replaceWhitespaces: {
        value: function(str = ',') {
            return this
                .trim()    // โญ๏ธ removes whitespace from both ends
                .replace(/\s+/g, str);
        },
    },

    // ๐Ÿ”ธ str.characters
    // - real characters (grapheme clusters, may contain many code points)
    characters: {
        get: function() {
            // string -> iterable iterator
            return splitter.iterateGraphemes(this);
        },
    },

    // ๐Ÿ”ธ str.codePoints
    // - 1 code point may contain 1 ~ 2 code units.
    codePoints: {
        get: function() {
            let codePoints = [];
            for (const char of this) {    // an iterator of "code points"
                codePoints.push(char.codePointAt(0));
            }
            return codePoints;
        },
    },

    // ๐Ÿ”ธ str.codeUnits
    // - 16-bit code units
    codeUnits: {
        get: function() {
            return [...range(0, this.length - 1).map(i => this.charCodeAt(i))];
        },
    },
});

// export
module.exports = {};

Last updated