LearnFrenzy
Sign in Take a free test

Scope and Hoisting · Exercise 4 of 4

Scope and Hoisting Scope and Hoisting Coding Problems

  • 10 questions
  • Page 1 of 1
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

JavaScript programs that use scope deliberately: private state with the module pattern, ID generators, loggers, a private stack and cart, running averages, toggles, a cache with expiry and lazy initialisation. Write each one yourself first, then open the solution – every solution was run on Node.js and the output shown is the real output.

Question 1 Medium

Write createAccount(owner, opening) that keeps the balance private and exposes deposit, withdraw (refusing overdrafts) and statement methods.

Question page & discussion
Question 2 Easy

Write makeId(prefix) that returns a function producing IDs like "USR-1", "USR-2", …, with separate sequences per prefix.

Question page & discussion
Question 3 Hard

Write rateLimit(limit, windowMs) returning a function allow(timestamp) that permits at most limit calls in any window of windowMs milliseconds. Test it with given timestamps.

Question page & discussion
Question 4 Medium

Write createLogger(name, minLevel) returning debug, info, warn and error functions that print only messages at or above minLevel, prefixed with the logger name.

Question page & discussion
Question 5 Medium

Write createStack() with push, pop, peek and size methods whose items array cannot be reached from outside, and use it to check balanced brackets.

Question page & discussion
Question 6 Medium

Write createCart() with add(name, price, qty), remove(name) and total() methods; items must stay private and adding an existing item must increase its quantity.

Question page & discussion
Question 7 Easy

Write makeAverager() that returns a function: each call adds a number and returns the average of all numbers so far.

Question page & discussion
Question 8 Easy

Write makeToggle(...options) that returns a function cycling through the options on each call (for example light → dark → system → light).

Question page & discussion
Question 9 Hard

Write createCache(ttl, clock) with get(key, compute) that returns a cached value while it is younger than ttl, and recomputes it otherwise. Use a fake clock so the result is predictable.

Question page & discussion
Question 10 Medium

Write lazy(init) that returns a getter which runs the expensive init function only on the first call and returns the same object afterwards.

Question page & discussion
All exercises doneBack to Scope and HoistingRevise the concepts or pick another topic

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links