WeakMap for Private Data in JavaScript
Level 5362 keystrokes
Uses WeakMap to store truly private data associated with class instances.
JavaScript code
// WeakMap stores key-value pairs where keys must be objects// Keys are weakly held, allowing garbage collection1const privateData = new WeakMap();2 3class User { // Constructor takes public name and private secret4 constructor(name, secret) { // name is a public property5 this.name = name; // Store secret in WeakMap using 'this' as key // This data is truly private - not on the object itself6 privateData.set(this, { secret });7 }8 // Method to verify the secret without exposing it9 checkSecret(guess) { // Retrieve private data using 'this' as key // Compare the stored secret with the guess10 return privateData.get(this).secret === guess;11 }12}13 // Create a user with a secret14const user = new User("Alice", "password123");// Public name is accessible15console.log(user.name);// Wrong guess returns false16console.log(user.checkSecret("wrong"));// Correct guess returns true17console.log(user.checkSecret("password123"));Output
Alice false true
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 11)× 11.× 10;× 8"× 8=× 6{× 4}× 4,× 3