@avolutions/canvas-painter
Version:
CanvasPainter.js is a simple yet powerful JavaScript library for drawing basic shapes (rectangles, circles, etc.) on HTML5 Canvas with ease. Perfect for creating 2D graphics in your web projects.
45 lines (44 loc) • 1.78 kB
JavaScript
/**
* A base class that implements ISerializable, providing functionality to serialize
* an object's properties to an array or a JSON string, including nested objects
* that implement the ISerializable interface.
*/
export class Serializable {
/**
* Converts the object's properties to an array. If any of the properties
* are objects that implement ISerializable, their `toArray` method is called.
*
* @returns An array representation of the object's properties.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
toArray() {
return Object.values(this).map(value => {
if (value && typeof value.toArray === 'function') {
return value.toArray(); // Call toArray for nested objects
}
return value; // Simple values
});
}
/**
* Converts the object to a JSON string. If any of the properties
* are objects that implement ISerializable, their `toJson` method is called.
* Underscores e.g. of private members are trimmed when setting the serialized name.
*
* @returns A JSON string representation of the object.
*/
toJson() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const jsonObject = {};
Object.entries(this).forEach(([key, value]) => {
// Trim leading underscore from private properties
key = key.split('_').join('');
if (value && typeof value.toJson === 'function') {
jsonObject[key] = JSON.parse(value.toJson()); // Call toJson for nested objects
}
else {
jsonObject[key] = value; // Simple values
}
});
return JSON.stringify(jsonObject);
}
}