Skip to content

Instantly share code, notes, and snippets.

@dotMastaz
Created October 9, 2024 13:07
Show Gist options
  • Save dotMastaz/0a1f9c29ea69254c5e7cf7d97319b65b to your computer and use it in GitHub Desktop.
Save dotMastaz/0a1f9c29ea69254c5e7cf7d97319b65b to your computer and use it in GitHub Desktop.
Js Factory DefaultObjectFactory createObjectWithDefaults
interface Product {
name: string;
price: number;
inStock: boolean;
}
type DefaultValues = {
string: string;
number: number;
boolean: boolean;
};
const defaultValues: DefaultValues = {
string: "",
number: 0,
boolean: false,
};
class DefaultObjectFactory<T> {
createObjectWithDefault(): T {
const obj: any = {};
(Object.keys(defaultValues) as Array<keyof T>).forEach((key) => {
const typeOfKey = typeof defaultValues[key as keyof DefaultValues];
switch (typeOfKey) {
case "string":
obj[key] = "";
break;
case "number":
obj[key] = 0;
break;
case "boolean":
obj[key] = false;
break;
default:
obj[key] = null;
}
});
return obj as T;
}
}
function createObjectWithDefaults<T>(): T {
const obj: any = {};
(Object.keys(defaultValues) as Array<keyof T>).forEach((key) => {
const typeOfKey = typeof defaultValues[key as keyof DefaultValues];
switch (typeOfKey) {
case "string":
obj[key] = "";
break;
case "number":
obj[key] = 0;
break;
case "boolean":
obj[key] = false;
break;
default:
obj[key] = null;
}
});
return obj as T;
}
// Function
const product = createObjectWithDefaults<Product>();
console.debug(" product : ", product);
// Factory
const factory = new DefaultObjectFactory<Product>();
const defaultProduct = factory.createObjectWithDefault();
console.debug("defaultProduct : ", defaultProduct);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment