This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
148. create a counter object
Here is one possible solution using a closure:
function createCounter() {
let count = 0;
return {
get count() {
return count++;
},
set count(value) {
console.error('Cannot assign a new value to count.');
},
};
}
Explanation:
- The function
createCounterreturns an object that contains two properties: a getter and a setter for thecountproperty. - The
countvariable is initialized to 0 using a closure. This variable is private and cannot be accessed from outside the object. - The getter function returns the current value of
countand increments it by 1. - The setter function throws an error when someone tries to assign a new value to
count. This makescounta read-only property. - The
console.errormethod is used to log the error message to the console.
Note: There are other ways to implement a counter object in JavaScript. This is just one example.