Skip to content
This repository was archived by the owner on Dec 27, 2023. It is now read-only.

Commit 7cb6bd1

Browse files
committed
add closure exercise
1 parent 30d9594 commit 7cb6bd1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

exercises/closure/README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Closure
2+
3+
This is an exercise to practice closure.
4+
5+
## Instructions
6+
7+
1. Modify `strBuilder(..)` so that it can take a string and return back a function.
8+
9+
**Note:** For purposes of this exercise, assume that `strBuilder(..)` itself is always called with a string initially.
10+
11+
2. For each call to a function here, if a string is passed, a function should be returned.
12+
13+
3. If a non-string is passed (such as passing no argument), a string value should be returned, which is the concatenation of all the passed in strings.
14+
15+
4. Hints:
16+
- You can use `typeof foo == "string"` to test if `foo` is a string.
17+
18+
- Look at the test cases at the bottom of the exercise file to clarify any questions about expected behavior.
19+
20+
- Ensure your function(s) are pure. Avoid mutating a closed over variable, which would be a side-effect.

exercises/closure/initial-exercise.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict'
2+
3+
function strBuilder (str) {
4+
return strBuilder
5+
}
6+
7+
var hello = strBuilder('Hello, ')
8+
var kyle = hello('Kyle')
9+
var susan = hello('Susan')
10+
var question = kyle('?')()
11+
var greeting = susan('!')()
12+
13+
console.log(strBuilder('Hello, ')('')('Kyle')('.')('')() === 'Hello, Kyle.')
14+
console.log(hello() === 'Hello, ')
15+
console.log(kyle() === 'Hello, Kyle')
16+
console.log(susan() === 'Hello, Susan')
17+
console.log(question === 'Hello, Kyle?')
18+
console.log(greeting === 'Hello, Susan!')

0 commit comments

Comments
 (0)