Good morning! Here's our prompt for today.
In JavaScript, closures and dependency injection are powerful concepts that enable modular, maintainable, and flexible code. In this challenge, you will explore these concepts by implementing a specific functionality using closures and then using closures for dependency injection.
Part 1: Closures
Closures allow a function to access variables from an outer function that has already finished its execution. Your task is to create a closure that serves as a decrementing counter.
Boilerplate code:
1var minus = (function () {
2 // TODO: Initialize a counter variable
3 // TODO: Return a function that decrements the counter and returns the current value
4})();
Part 2: Dependency Injection with Closures
Dependency Injection is a technique where one object supplies the dependencies of another object. You will create a function that returns factories for sending email and SMS messages, and these factories will use a logger function passed as a dependency.
Boilerplate code:
1function createFactories(logger) {
2 // TODO: Return an object containing emailFactory and smsFactory
3 // emailFactory should take a greeting and return a function that takes a greet and logs it using the logger
4 // smsFactory should take a text and return a function that logs the text using the logger
5}
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
var assert = require('assert');
/*
* Closures
*/
var minus = (function () {
var counter = 999;
return function () {
counter -= 1;
return counter;
};
})();
minus();
minus();
minus();
/*
* Dependency Injection With Closures
*/
function createFactories(logger) {
return {
emailFactory: function (greeting) {
return function (greet) {
logger(greeting + greet);
};
},
smsFactory: function (text) {
return function (text) {
Here's how we would solve this problem...
How do I use this guide?