💾ownPropertyFlags(obj)

JSvaluesobjectpropertyflag ⟩ ownPropertyFlags()

// Dependencies:
// 🔸 ownPropertyFlags --> typeName --> isClass

"use strict";

const { log } = console;

// table of own property flags
// 🔸 require: typeName()
function ownPropertyFlags(obj, {
    showFooter = true,
    objectName = null,
} = {}) {

    // padding between columns
    const pad = '   ';

    // convert descriptor (object) into string.
    function descripterToString(prop, descriptor, propNameColWidth) {

        const on = 'v', off = '.', icon = '🔸';

        let result = icon + prop.padEnd(propNameColWidth + 2, ' ') + pad;
        result += (descriptor.writable ? on : off) + ' ';
        result += (descriptor.enumerable ? on : off) + ' ';
        result += (descriptor.configurable ? on : off);
        result += pad;

        // check "value"
        const value = descriptor.value;
        switch (typeof value) {
            case 'function':
                result += `${value.name || '[no name]'} (${typeName(value)})`;
                break;
            default:
                result += `${value}`;
        }

        return result
    }

    // get all (own) property descriptors
    const descriptors = Object.getOwnPropertyDescriptors(obj);
    // get all property names
    const keys = Object.getOwnPropertyNames(descriptors);
    // property name column width
    const keyColumnWidth = Math.max(...keys.map(key => key.length));

    // map all descriptors into array of strings
    const lines = keys
        .map(key => descripterToString(key, descriptors[key], keyColumnWidth));

    // calculate table width
    const tableWidth = Math.max(...lines.map(line => line.length));

    // compose table content
    const divider = '-'.repeat(tableWidth) + '\n';
    const title = `${objectName || obj.name || '[no name]'} (${typeName(obj)})\n`;
    const header = '  property'.padEnd(keyColumnWidth + 4, " ")
        + pad + 'w e c' + pad + 'value\n';
    const footer = 'w: writable, e: enumerable, c: configurable\n';

    let tableContent = title + divider + header + divider
        + lines.join('\n') + '\n'
        + divider;

    if (showFooter) tableContent += footer;

    log(tableContent);
    return tableContent;
}

Last updated