Files
portfolio2023/node_modules/@poppinss/utils/build/src/Helpers/ObjectBuilder.js
T
2023-11-24 22:35:41 +01:00

76 lines
1.7 KiB
JavaScript

"use strict";
/*
* @poppinss/utils
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectBuilder = void 0;
/**
* A simple class to build an object incrementally. It is helpful when you
* want to add properties to the object conditionally.
*
* Instead of writing
* ```
* const obj = {
* ...(user.id ? { id: user.id } : {}),
* ...(user.firstName && user.lastName ? { name: `${user.firstName} ${user.lastName}` } : {}),
* }
* ```
*
* You can write
*
* const obj = new ObjectBuilder()
* .add('id', user.id)
* .add(
* 'fullName',
* user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : undefined
* )
* .value
*/
class ObjectBuilder {
constructor(ignoreNull) {
this.ignoreNull = ignoreNull;
this.value = {};
}
/**
* Add value to the property.
*
* - Undefined values are ignored
* - Null values are ignored, when `ignoreNull` is set to true
*/
add(key, value) {
if (value === undefined) {
return this;
}
if (this.ignoreNull === true && value === null) {
return this;
}
this.value[key] = value;
return this;
}
/**
* Remove value from the object
*/
remove(key) {
delete this.value[key];
return this;
}
/**
* Find if a value exists
*/
has(key) {
return this.get(key) !== undefined;
}
/**
* Get the existing value
*/
get(key) {
return this.value[key];
}
}
exports.ObjectBuilder = ObjectBuilder;