predictype
Version:
PredicType is a library of pre-built and tested predicates for TypeScript, covering various data types and operations.
51 lines (50 loc) • 2.1 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.objectAttributes = objectAttributes;
const objects_js_1 = require("../../enums/objects.js");
/**
* Checks object property attributes (writable, enumerable, configurable, accessor, data property) using the specified
* operation.
*
* @param source The object to check.
* @param oper The attribute operation to perform (e.g. 'is_writable', 'is_accessor').
* @param key The property key to check.
* @returns True if the attribute check is valid according to the operator, otherwise false.
*
* @throws {Error} If the operation is not recognized.
*
* @example
* const obj = { foo: 42 };
* const obj2 = {};
* const sym = Symbol('bar');
*
* Object.defineProperty(obj2, sym, { value: 1, writable: false });
*
* objectAttributes(obj, 'is_writable', 'foo'); // true
* objectAttributes(obj2, 'is_writable', sym); // false
*
* @remarks
* Supported Operators:
* - **ATTR_IS_WRITABLE**: Property is writable
* - **ATTR_IS_ENUMERABLE**: Property is enumerable
* - **ATTR_IS_CONFIGURABLE**: Property is configurable
* - **ATTR_IS_ACCESSOR**: Property is an accessor (getter/setter)
* - **ATTR_IS_DATA_PROPERTY**: Property is a data property
*/
function objectAttributes(source, oper, key) {
const desc = Object.getOwnPropertyDescriptor(source, key);
if (!desc)
return false;
const operators = {
[objects_js_1.ObjectAttributesEnum.ATTR_IS_WRITABLE]: (d) => !!d.writable,
[objects_js_1.ObjectAttributesEnum.ATTR_IS_ENUMERABLE]: (d) => !!d.enumerable,
[objects_js_1.ObjectAttributesEnum.ATTR_IS_CONFIGURABLE]: (d) => !!d.configurable,
[objects_js_1.ObjectAttributesEnum.ATTR_IS_ACCESSOR]: (d) => typeof d.get === 'function' || typeof d.set === 'function',
[objects_js_1.ObjectAttributesEnum.ATTR_IS_DATA_PROPERTY]: (d) => 'value' in d,
};
const enumOper = typeof oper === 'string' ? oper : oper;
const fn = operators[enumOper];
if (!fn)
throw new Error(`Unknown ObjectAttributes operation: ${oper}`);
return fn(desc);
}
;