Skip to content

Instantly share code, notes, and snippets.

@codeAdrian
Created May 2, 2023 07:07
Show Gist options
  • Save codeAdrian/a76ad2350d218c36121fcc57fbad6a5f to your computer and use it in GitHub Desktop.
Save codeAdrian/a76ad2350d218c36121fcc57fbad6a5f to your computer and use it in GitHub Desktop.
/* UTILS */
const getFullName = (firstName, lastName, middleName) =>
[firstName, middleName, lastName].filter((n) => !!n).join(" ");
const getFormattedBalance = (locale, currency, value) => {
return new Intl.NumberFormat(locale, {
style: "currency",
currency
}).format(value);
};
/* PROXY */
const handleFullGet = (obj, prop) => {
if (prop === "fullName") {
return getFullName(
Reflect.get(obj, "firstName"),
Reflect.get(obj, "lastName"),
Reflect.get(obj, "middleName")
);
}
if (prop === "balance") {
return getFormattedBalance(
Reflect.get(obj, "locale"),
Reflect.get(obj, "currency"),
Reflect.get(obj, "balance")
);
}
if (!(prop in obj)) {
console.error(`${prop.toString()} doesn't exist in object`, obj);
return;
}
return Reflect.get(obj, prop);
};
const createUserDataProxy = (user) => {
const proxy = new Proxy(user, {
get: handleFullGet
});
return proxy;
};
/* USE */
const user = createUserDataProxy({
firstName: "John",
middleName: "",
lastName: "Doe",
email: "john.doe@email.com",
balance: 2649.53,
currency: "USD",
locale: "en-US"
});
console.log(user.fullName); // John Doe
console.log(user.balance); // $2,649.53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment