text:
To read more about which files Bash runs at which times at this link:
https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html

### Zsh startup files

The `.zshrc` file is started anytime you start Zsh for both _login shells_ and
_non-login_ shells. It does have a `.zlogin` file which is only executed on
login shells but since `.zshrc` loads on both most Zsh users don't use `.zlogin`
and instead put all their customizations in `.zshrc`.

To read more about all Zsh's various startup files you can follow this link:
http://zsh.sourceforge.net/Intro/intro_3.html

## To Login or Not to Login

So how can you tell if you have a login shell or a non-login shell? It depends
on how your operating system works.

### macOS

On macOS prior to Catalina if you open the Terminal
application, it runs Bash as a _login shell_ and therefore runs the
`.bash_profile` on every terminal window you open.

After macOS Catalina, if you open the Terminal application it launches Zsh
as a _login shell_ and therefore runs both `.zlogin` and `.zshrc`.

### Windows using WSL

On Windows using WSL, the Windows Ubuntu terminal app runs every bash
as a _login-shell_ and therefore will run the `.profile`.

### Ubuntu Linux

On Ubuntu Linux, by default the `.profile` is executed when
you login to the Ubuntu Desktop. Ubuntu does not include `.bash_profile` by
default. Then when you open the Terminal application, it runs each bash as a
_non-login shell_ which only runs `.bashrc`.

This can be somewhat frustrating to have to logout of the Ubuntu Desktop and
login back in each time you change your startup file. So instead you can change
the Terminal application to run each shell as a login shell by checking this
checkbox in the Terminal preferences that reads _"Run command as a login shell"_

![Ubuntu Terminal]

### Visual Studio Code

When you use Visual Studio Code's integrated terminal, on macOS it defaults
to being a login shell, while on Linux and Windows it does not.

You can change the integrated shell in vscode on Ubuntu and Windows using WSL
by modifying or adding these settings in the VSCode `settings.json` file.

```json
  "terminal.integrated.shell.linux": "bash",
  "terminal.integrated.shellArgs.linux": [ "-l" ]
```

If you use macOS Catalina, VSCode will still default to bash in it's integrated
shell, so you can set it to use Zsh like so:

```json
  "terminal.integrated.shell.osx": "zsh",
  "terminal.integrated.shellArgs.osx": [ "-l" ]
```

### Whew this seems complicated, can you just tell me which file to use?

Sure, here's our recommendations on how to customize your system depending on
platform to have the best results.

#### macOS Catalina with Zsh

- Put your customizations into your `.zshrc` file.
- Change Visual Studio Code to use `zsh` as it's shell.

#### macOS pre-Catalina with Bash

- Put your customizations into your `.bash_profile` file.

#### Ubuntu Linux

- Change your terminal to open login shells
- Put your customization into your `.profile` file.
- Change Visual Studio Code's integrated terminal to launch login shells as well.

#### Windows with WSL

- Put your customization into your `.profile` file.
- Change Visual Studio Code's integrated terminal to launch login shells as well.

### Customization options

Whew, that's a lot of new jargon & theory! Let's look at some practical examples
of what you can do with your dotfiles in Bash or Zsh.

Adding new options to your dotfiles starts with editing them.

You can open them directly from the command line using VS Code:

```sh
$ code ~/.bash_profile
# OR
$ code ~/.bashrc
# OR for Zsh
% code ~/.zshrc
```

Once you've saved your changes, you'll need to load any updated files into your
shell. You can do ths with the `source` command. `source` will execute the file
it's given, updating your currently-running environment with any changes you've
made:

```sh
# For Bash
$ source ~/.bash_profile
```

OR

```sh
# For Zsh
% source ~/.zshrc
```

One of the most common customizations are environment variables. These should
always be capitalized & use underscores instead of spaces to delineate words.
Here are a couple examples of code customizing environment variables, along with
comments explaining how each works.

```sh
# The simplest option: adding a totally new environment variable.
export FAVORITE_COLOR=blue

# Let's overwrite an existing environment variable with our own.
export HOME=/User/Student/Home

# Time to get get more creative: what if we want to _prepend_
# to the PATH variable, instead of overwriting it if it exists?
export PATH=/User/Student/Applications:$PATH
```

In that last example, notice how we used `$` before `PATH`. The dollar sign
indicates that we're referencing a variable. Bash will replace `$PATH` with the
value of the `PATH` variable, so we're effectively adding our own directory to
the beginning of the `PATH` variable. You'll see this technique used a **lot**
in dotfiles.

Another common customization is aliasing. An _alias_ is a shorthand way of
running a command. You might alias because a command is very long to type, or to
modify the system's default behavior! Here are some examples:

```sh
# Here's a Git alias that will save you a few keystrokes.
alias gst="git status"

# Some more Git magic: show the short log with an even shorter command!
alias glog="git log --oneline"

# By default, 'rm' will remove the file you pass it. The '-i'
# option makes 'rm' ask you "Are you sure?" before removing the
# given file. This is a great safety net to have while you're learning!
alias rm="rm -i"
```

Don't forget to `source` your dotfiles if you're following along!

Entering an alias on the command line makes the aliased command act just like
the full command was entered. You can still pass arguments like you normally
would! Here are some "before & after" examples of our aliases in action:

Notice how we get the same output from `gst` as `git status` with significantly
less typing.

Our `glog` alias provides us with a short, quick-to-read commit history that
takes even fewer characters typed than the default `git log`!

The `rm` alias is an example of changing the default behavior of a command.
Before we aliased `rm`, removing a file happened with no confirmation at all.
After the alias is applied, we see a prompt that lets us respond "y" (for
"**y**es") or "n" (for "**n**o"). Think of this as the command line version of a
"Confirm" or "Cancel" pop-up window!

## What we've learned

We're diving deeper behind the scenes of our terminal & operating system, and
hopefully you're beginning to understand how things work together! You should
now be comfortable with:

- What a "shell" is in computer terms,
- explaining, at a very high level, how your computer interprets your commands,
- reading and redefining the `PATH` environment variable,
- and customizing your system via _dotfiles_

[prior to Catalina which uses Zsh]: https://support.apple.com/en-us/HT208050
[Zsh in macoS Catalina]: https://support.apple.com/en-us/HT208050
[Ubuntu Terminal]:https://-open-assets.s3-us-west-1.amazonaws.com/Module-Unix/cli/assets/cli-shell-basics-ubuntu-terminal.png
[Terminal]:https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/DEC_VT100_terminal_transparent.png/675px-DEC_VT100_terminal_transparent.png
________________________________________________________________________________
# Bash Permissions & Scripting

Now that you're familiar with Bash, let's get back to what we're all here for:
PROGRAMMING! We'll discuss the basics of Bash scripting, including:

- Creating a new script file,
- Accepting user input and conditionally responding to it,
- Modifying permissions to make the script executable,
- and choosing how to execute your script (or any other application).

## Understanding `sudo` and file permissions

Before we can write any code, we need to get a quick look at file permissions in
UNIX-based operating systems. Without understanding this critical part of file
management, you'll have a difficult time creating new scripts of your own.

Remember the command/option combo `ls -al`? We'll focus in particular on the
`-l` command line option, which **l**ists the files in the directory along with
their metadata. This includes their _file permissions_ (also sometimes referred
to as _modes_). Permissions determine who can access a given file or directory.

Here's an example of what a directory and file look like via `ls -al`:

The file permissions are the ten characters on the left side of each line. Let's
break them down:

The leftmost position is the _directory indicator_. This is the easiest part to
read! You'll see a `d` for directories and a `-` for files.

The remaining nine characters are broken into groups of three, representing the
_owner_, _group_, and _others_ from left to right. Each group has three
permissions available:

- _read (r)_: view a file or directory's contents
- _write (w)_: modify a file or directory's contents
- _execute (x)_: run a file like an application, navigate into a directory

A letter in any position means that permission is _granted_, while a `-` means
the permission is _restricted_.

In our example above, we can see that the owner (`jdh`) of the file
`my-shared-timeline.zip` can view the file or edit it, but the group (`staff`)
and world (everyone else) can only view it. No one is allowed to execute the
file, but that makes sense in this case: `x` permissions are mostly used by
scripts/applications and directories.

### Numeric permission notation

While the letters `r`, `w`, and `x` are easy to read, you'll also see a numeric
notation for file permissions. To convert letter notation to numeric, you'll
need to grant each permission a number value. `x` is worth 1, `w` is worth 2,
and `r` is worth 4. Now, tally up points for each group and write them out side
by side.

From our example above, we'd get `644`. This is the numeric notation for the
permissions of `my-shared-timeline.zip`. You'll sometimes see these numeric
formats referenced in documentation or Bash error messages, so it's good to know
how to read them even if you don't use them often!

Numeric permissions are presented in _octal notation_. You can read a few more
details about how this works on [LinuxCommand.org][LinuxCommand octal
permissions].

### Modifying permissions

We're not stuck with the permissions a file starts with! We can use the `chmod`
command to update the permissions of a file ourselves. `chmod`, short for
"**ch**ange **mod**e", dates back to the early days of UNIX. You may hear it
pronounced as "cha-mod", "see-aych-mod", or even referred to as "change mod".

Let's say we've written a cool "How To" guide that we'd like to share with all
users of our system. Assume we're starting with permissions where the owner can
read or update the file but no one else can even read it (`-rw-------` or
`600`).

To change this so that anyone on the system can read it, we could run:

```sh
> chmod +r my-guide.txt
```

This is saying "Add the 'r' permission for all users who try to access
`my-guide.txt`.

To _revoke_ that permission, you can exchange `+` for `-`:

```sh
> chmod -r my-guide.txt
```

Uh oh! If we check `my-guide` now, we'll see that we're not back at `-rw-------`
- we're now at `--w------`! When you change permissions using letter notation
  and don't specify a target group, the change affects **all three** groups at
  once. You can scope this down by preceding the operator with either `u` (for
  **user**, meaning the file's owner), `g` (for the file's owning **group**),
  and `o` (for **others**).

Let's add read permissions back for the owner:

```sh
> chmod u+r my-guide.txt
```

Perfect! Now we've reverted our permissions back to their original state.

### Ignoring permissions entirely with sudo

Most systems include a _root_ user that has total authority. The root user can
run applications and change files indiscriminately. With that much power, it's
hard to keep a system safe! For this reason, it's a bad practice to log in as
`root`.

To keep us from having to memorize both our own password and that of the `root`
account for every system, we've got a helpful command called `sudo`. `sudo` is
short for "**S**uper **U**ser **Do**", and as the name implies it allows you to
impersonate the `root` user for a particular task.

**`sudo` is inherently dangerous.** Every time you use it, you're at risk of
doing real damage to the system you're on. While there are some [advanced
safeguards & security features][sudo manpage] for the `sudo` command, it's best
to use is sparingly if at all.

Generally, applications will provide a message letting you know if `sudo` is
needed. This might include installing new applications or browsing system
configuration files. These decisions are only as safe as you make them, so be
sure you're confident about the changes you're making before using `sudo`.

There's a common trap we've mentioned before where `sudo` comes up frequently:
the `rm` command. Using `rm` indiscriminately as an unprivileged user can cause
you some frustration but is unlikely to do any permanent damage. Using `sudo rm`
in any capacity can wreak havoc on a system and may result in significant data
loss.

**Never use `sudo` with `rm` or with code from the internet that you don't
understand!**

## Bash scripting

Let's talk about scripting. We've used the word "script" quite a few times
already, but what exactly is it? A _script_ is simply a text file that we've
granted permission to execute on our system.

You'll have lots of opportunities to run scripts for everything from setting up
your environment on a new computer to installing new applications. Writing your
own scripts is a great way to automate repetitive tasks.

### Script requirements

An effective script requires three things:

- An interpreter directive
- A commented description
- A script body

The _interpreter directive_ (more commonly called the _shebang_) is the first
line of the script file. It's used by the operating system to know which
application should be used to run your code.

> Why "shebang"? This name is a combination of two words: _hash_, a reference to
> the octothorpe symbol (`#`) and _bang_, a reference to the exclamation point
> (`!`). Helpfully, the "shebang" nickname will also help you remember in which
> order these characters are expected!

Here's an example shebang for a Bash script:

```
#!/bin/bash
```

Adding that line to the top of your script file lets the system know that you'd
like to use the application `/bin/bash` to run your script file. As you learn
more scripting languages, you can change change the shebang to make sure the
script's language matches its executing environment.

The commented description is a best practice. Your script won't fail to run
without it, but saving scripts without comments is a dangerous game - if you
forget what it is or how it works, you won't have any reference to help re-learn
it! Investing a few minutes in a good comment explaining why you're writing this
script will save you a few of hours of headache down the road. Comments in Bash
scripts must be preceded by an octothorpe (`#`) on each line.

The script body is where the magic happens. Here, you'll write commands just as
you would enter them on your command line, and they'll be sequentially executed
to complete the script. Each line should include a separate command.

### A sample script

Here's a very simple "Hello World!" application in Bash:

```sh
#!/bin/bash

# "Hello, World!" by Alex Martin
#
# Prints a friendly message to the screen

echo "Hello, World! "
```

Notice that we've got all three of our key ingredients for a successful script.
All we need is to copy this script into an empty file and make it executable.

### Updating & running a script

Once you've written your script into a new file, you need to make that file
executable. For security, your system won't run just any file! You'll need to
mark it "safe" through the magic of `chmod`.

Assuming our script is called `hello-world`, this will make the file executable:

```sh
> chmod +x hello-world
```

We can now run it simply by invoking the file:

```sh
> ./hello-world
Hello, World!
```

Notice how we used `./` before the script. This isn't strictly necessary, but
it's a good habit to get into. If we ran just `hello-world` and happened to have
an application called "hello-world" available in our `PATH`, we might never make
it to our own script! Preceding the script name with `./` ensures we're going to
the run the script with that name in the current directory.

## What we've learned

We've covered some of the basics of files and security, and we've looked at
Bash's native scripting support. After this lesson you should be able to:

- explain the basics of file permissions from `ls -l` output,
- read and modify file permissions from the command line,
- create and a run a small Bash script.

[LinuxCommand octal permissions]: http://linuxcommand.org/lc3_lts0090.php
[sudo manpage]: http://manpages.ubuntu.com/manpages/trusty/man8/sudo_root.8.html

________________________________________________________________________________
# WEEK-03 DAY-4
*Recursion* {ignore=true}
________________________________________________________________________________
# Recursion Learning Objectives

Below is a complete list of the terminal learning objectives for this lesson.
When you complete this lesson, you should be able to perform each of the
following objectives. These objectives capture how you may be evaluated on the
assessment for this lesson.

1. Given a recursive function, identify what is the base case and the recursive
 case.
2. Explain when a recursive solution is appropriate to solving a problem over
 an iterative solution.
3. Write a recursive function that takes in a number, n, argument and
 calculates the n-th number of the Fibonacci sequence.
4. Write a function that calculates a factorial recursively.
5. Write a function that calculates an exponent (positive and negative)
 recursively.
6. Write a function that sums all elements of an array recursively.
7. Write a function that flattens an arbitrarily nested array into one
 dimension.
8. Given a buggy recursive function that causes a RangeError: Maximum call
 stack and examples of correct behavior, debug the function. learning objectives for this lesson.
When you complete this lesson, you should be able to perform each of the
following objectives. These objectives capture how you may be evaluated on the
assessment for this lesson.

1. Given a recursive function, identify what is the base case and the recursive
 case.
2. Explain when a recursive solution is appropriate to solving a problem over
 an iterative solution.
3. Write a recursive function that takes in a number, n, argument and
 calculates the n-th number of the Fibonacci sequence.
4. Write a function that calculates a factorial recursively.
5. Write a function that calculates an exponent (positive and negative)
 recursively.
6. Write a function that sums all elements of an array recursively.
7. Write a function that flattens an arbitrarily nested array into one
 dimension.
8. Given a buggy recursive function that causes a RangeError: Maximum call
 stack and examples of correct behavior, debug the function.

________________________________________________________________________________
# Re-learning Functions With Recursion

Imagine it's your first day at a new job and your boss has asked you to unpack
some fruit crates. Not too bad, right? Now imagine each crate has smaller crates
inside. Still easy? Consider even smaller crates, nested within one another,
each needing to be unpacked. How long before you throw your hands up in
frustration and walk away?

Sometimes simple tasks get complicated and we need new tools to help us solve
them. Working with digital data is a little like working with those crates: they
may be simple to unpack, or they may be incredibly dense! Let's explore a new
way of approaching problems: _recursion_.

We'll cover:

- what recursion is and how to identify it,
- implementing recursive functions,
- and breaking complex problems down into simpler tasks.

## Re-what now?

So far, we've solved complex problems with _iteration_: the process of counting
through each item in a collection. Like most things in programming, though,
there's another way! Let's check out _recursion_: the process of calling a
function within itself.

To wrap your mind around this new concept, think back to that example of crates
within crates. If we have to gently unpack each crate but we don't know the
contents, we'll have to go one-by-one through each crate, pulling items out
individually. Let's think about a better way! What if we open each crate and
look inside. If it's more crates, we dump them out. If it's fruit, we gently
remove the fruit and set it aside.

What might this process look like in code? Here's some pseudocode to help us
think through it:

```js
function gentlyUnpackFruit(contents) {
  console.log("Your " + contents + " have been unpacked!");
}

function dump(crate) {
    if (crate.content_type === "crate") {
        dump(crate.contents);
    } else if (crate.content_type === "fruit") {
        gentlyUnpackFruit(crate.contents);
    }
}
```

Notice how we call the `dump` function from **within** the `dump` function.
That's recursion in action! The `dump` function may _recurse_ if we have crates
nested within each other.

### A note on language

You'll notice we've used the term _recurse_ here, which you may not have heard
before. Technically, the root word in "recursion" is "recur", but this is
ambiguous. Consider these two examples:

```js
console.log("Hello"); console.log("Hello");

// versus...

console.log(console.log("Hello"));
```

Both of these functions **recur** (as in, call the `console.log` function more
than once), but only one of these functions is **recursive** (as in, calling
`console.log` from within another `console.log`). To reduce confusion,
researchers began using the term ["recurse"][1] to refer specifically to
functions that are being called from within themselves. Creating a new word by
removing a suffix in this way is known as _back-formation_.

We'll prefer "recurse" when discussing this topic, but you may see "recur" in
other places! Carefully read the context and make sure you understand how these
words might differ. Interviewers may use the terms interchangeably to trip you
up, but we know you'll be ready for the challenge!

## Two cases

Understanding recursion means understanding the two _cases_, or expected output
for a particular input, in a recursive function. These are known as the _base
case_ and _recursive case_.

- The _base case_ describes the situation where data passed into our function is
  processed without any additional recursion. When the base case is executed,
  the function runs once and ends. Since this results in the function stopping,
  we may also refer to this as the _terminating case_.

- The _recursive case_, as the name suggests, is the situation where the
  function recurses. This represents the data state that causes a function to
  call itself. Without a recursive case, a function's just another function!

In our fruit crate example, the base case is "when the crate contains fruit" and
the recursive case is "when the crate contains other crates". When we encounter
fruit, we remove the fruit and the action is complete. However, when we
encounter more crates, we go back to the start and repeat the whole process
again.

Identifying these cases for a process won't always be that simple, but it's
critical to figure out each one before writing any code. Without a recursive
case, we don't need recursion at all, and we should consider an alternative
approach. Without a base case, we might be creating an _infinite loop_ - yikes!
We need to know when to stop the process before we start it.

## A recursive example

Let's look at a more practical problem you might encounter in the wild. We're
going to use the "Movie Theater Problem" to demonstrate how recursion can help
us with a real world issue.

Imagine you're meeting a friend in a movie theater. The lights have gone down,
it's totally dark, and your friend just sent you a message asking which row
you're seated in. Without being able to see the rows or your ticket, how might
you figure out the row number?

Let's assume a few things:

- The theater is mostly occupied, so you can rely on people being in front of &
  behind you.
- You don't want to knock over anyone's drinks & snacks, so you must remain in
  your seat.
- Your phone is almost dead, so you can't use the flashlight or screen to
  illuminate the seats - no cheating!

What if we tap the person in front of us on the shoulder? If there's someone in
front of us, we know that we're at least one row back from the front of the
theater. If someone is in front of **them**, we're at least **two** rows back!
This pattern continues until we reach the screen.

If each person performs this action and they all report back, we can
count how many rows back we are! We've missed a key part in this analysis,
though - when do we stop tapping each other?  That person becomes "Row #1", and our test stops.

In this example, our base case is "No one in front of me = Row #1" and our
recursive case is "Someone in front of me = Row #(1 + person in front of me's
row #)". Now the we know both cases, we can build a recursive function out of
them! Here's what this might look like in JavaScript:

```js
determineRow = function(moviegoer) {
  if (moviegoer.personInFront) {
      return 1 + determineRow(moviegoer.personInFront);
  } else {
      return 1;
  }
}
```

Now it doesn't matter if our movie theater has 5 rows or 5,000 rows - we have a
tool to figure out where we are at any time. We've also gone through an
important exercise in understanding our space to get here! By working to our
sides instead of in front of us, we could use the same process to figure out
exactly which seat we're in on the row.

## What we've learned

Whew! If your head is spinning, don't worry - it's totally natural. Recursion
can get a lot mre complex than what we've covered here, but it comes down to
working smarter, not harder. We'll dig a little deeper into advanced recursion
and how to know when to build a recursive function in our next lesson.

Check out Computerphile's [What on Earth is Recursion?](https://www.youtube.com/watch?v=Mv9NEXX1VHc) to learn more about recursion and the stack.

After completing the reading and video, you should be able to:

- define _recursion_,
- explain its use,
- and identify a simple base & recursive case in a problem.

[1]: https://en.wiktionary.org/wiki/recurse

________________________________________________________________________________
# When To Hold & When To Fold(Fold(Fold())): Recursion vs. Iteration

We know what _recursion_ is, but to truly understand what's happening, we need
to go deeper! Let's investigate the process of recursion and build a better
understanding of the risks involved.

We'll cover:

- recursion and the call stack,
- differentiating recursive and iterative functions,
- and know when to use each tool for maximum effect.

## A deeper dive into recursion

Learning about recursion requires that we review the _call stack_. Remember that
each function call in JavaScript _pushes_ a new _stack frame_ onto the top of
the call stack, and the last pushed frame gets _popped_ off as it gets executed.
We sometimes refer to this as a _Last In, First Out_, or _LIFO_, stack.

Here's an example to jog your memory:

![Stack trace reminder from "Call Stack" lesson][stack-trace-04]

Recursive functions risk placing extra load on the call stack. Each recursive
function call depends on the call before it, meaning we can't start executing a
recursive function's stack frames until we reach the _base case_. So what
happens if we never do? Look out!

### London Stack is falling down!

The JavaScript call stack has a size limit which varies between different
browsers and even different systems! Once the stack reaches this limit, we get
what's called a _stack overflow_. The program halts, the stack gets wiped out
entirely, and we're left with no results wondering what we did wrong.

![Stack overflow example with call stack][stack-overflow]

Let's look at an example of an obvious stack overflow issue:

```js
function pythagoreanCup() {
    pythagoreanCup();
};

pythagoreanCup();
```

Output:
```plaintext
Uncaught RangeError: Maximum call stack size exceeded
    at pythagoreanCup (<anonymous>)
    at pythagoreanCup (<anonymous>)
    at pythagoreanCup (<anonymous>)
    at pythagoreanCup (<anonymous>)
    at pythagoreanCup (<anonymous>)
    ...
```

The function `pythagoreanCup` is clearly recursive, since it calls itself, but
we're missing a base case to work towards! This means the function will recurse
until the call stack overflows, resulting in a `RangeError`. Whoops! Notice that
in our _stack trace_ (the output below the error name & message), we can see
that `pythagoreanCup` is the only function currently in the call stack.

Fixing the overflow issue in this case is straightforward: determine a base case
and implement it in your function. Here's a fixed version of the example above
with some extra comments:

```js
let justEnoughWine = false;

function pythagoreanCup() {
    // Base case:
    // - Is `justEnoughWine` true? Return & exit.
    if (justEnoughWine === true) {
        console.log("That's plenty, thanks!");
        return true;
    }

    // Recursive case:
    // - justEnoughWine must not have been true,
    //   so let's set it and check again.
    justEnoughWine = true;
    pythagoreanCup();
};

pythagoreanCup();
```

Output:
```plaintext
"That's plenty, thanks!"
```

> The stack size limit varies due to different implementations: some JavaScript
> environments might have a fixed limit, while others will rely on available
> memory on your computer. Regardless of your environment, if you're receiving
> `RangeError`s, you should refactor your function! It's bad practice to build
> software that only runs in one particular browser or using a specific runtime.

### Step by step

Notice that our change to `pythagoreanCup` did two things:

- Provided a base case that lets us end the recursion,
- and added an action that moves us **towards** the base case.

Without changing the value of `justEnoughWine`, we would never enter the base
case and our stack would still be at risk of growing out of control.

We refer to the action that gets us closer to the base case as the _recursive
step_. Don't forget to build this step into your function! Your base case
doesn't mean anything if you're not moving towards it with each recurrence.

### Types of recursion

Our examples of recursion so far have involved a single function calling itself.
We refer to this situation as _direct recursion_: functions directly calling
themselves. There's a trickier type of recursion to debug, though. Take a look
at the following example:

```js
function didYouDoTheThing() {
    ofCourseIDidTheThing();
}

function ofCourseIDidTheThing() {
    didYouDoTheThing();
}

didYouDoTheThing();
```

Uh oh! Neither of these functions appears to be recursive by itself, but calling
either of them will put us into a recursive loop with no base case in sight. We
refer to recursive loops across multiple functions as _indirect recursion_.
There's nothing wrong with using this technique, but be careful! Because the
call stack will have multiple function names in it, debugging problems with
indirectly recursive functions can be a headache.

## When to iterate, when to recur

Alright, slow down, programmers. Before you rewrite all your recent projects to
use recursive functions, let's investigate why you might choose iteration
instead.

Remember that _iteration_ is when we call a function for each member of a
collection, instead of letting the function call itself. So far, the code you've
written using `for` loops and iterator functions like `.forEach` has been
_iterative_. Iterative code tends to be less resource-intensive than recursive
code, and it requires less planning to get working. It's also usually easier to
read & understand - an important thing to consider when writing software!

Iterative approaches tend to break down when our data becomes _very complex_ or
_very large_. Consider the task of sorting paper folders by the number of files
in each. If you only had a few folders, this wouldn't be very daunting, and you
could take an iterative approach: open each folder individually, count the
files, and place the folders in the correct order.

However, if you had thousands or even millions of folders, iteration would take
days instead of minutes. You'd want time to implement a system for getting
through those folders efficiently, and that system would likely involve a
procedure for ordering in batches. This is exactly what recursive functions do
best: repetitive processes on subsets of given data.

Consider recursion when your inputs are unpredictable, large, or highly complex.
Otherwise, iteration will almost always be the best approach. We'll look at lots
of examples to help you get a feel for this before someone asks you to identify
the best approach to a given problem in an interview

## Compare these approaches

Before we move on, let's compare an iterative & recursive approach with each
other. We'll create a `countdown` function that takes a number and counts down
from that number to zero.

Here's an iterative approach:

```js
countdown(startingNumber) {
    for(let i = startingNumber; i > 0; i--) {
        console.log(i);
    }

    console.log("Time's up!");
}
```

For comparison, a recursive approach:

```js
  countdown(startingNumber) {

      if (startingNumber === 0) {
          console.log("Time's up!");
          return;
      }

      console.log(startingNumber);
      countdown(startingNumber - 1);
  }
```

Can you identify the base case, recursive case, and recursive step?

## What we've learned

We're now equipped to solve problems of varying complexity with two different
approaches! Don't forget to be considerate of which approach might be best for
new challenges you encounter.

After completing this lesson, you should be able to:

- define "stack overflow" and debug functions causing one,
- differentiate between iterative and recursive functions,
- and identify good candidates for each type of approach.

[stack-trace-04]:
  https://-open-assets.s3-us-west-1.amazonaws.com/Module-JavaScript/asynchronous-functions/assets/stack-trace/04.png
[stack-overflow]:
  https://-open-assets.s3-us-west-1.amazonaws.com/Module-JavaScript/recursion/assets/image-recursion-stack-overflow.png

________________________________________________________________________________
# Recursion Problems

Here we `go(go(go()))`! It's time to flex your coding muscles on recursion. For
each problem, implement a **recursive** function that satisfies all the listed
requirements. Iterative solutions will be considered incorrect. The problems
aren't dependent on each other and may be completed in any order you wish.

As you complete each problem, use `mocha` to test your solutions. Make sure
you're in the project's root: you should be in the same place as the `problems/`
and `test/` directories. Once there, run the following command:

```sh
> mocha
```

Having trouble? Reach out to a TA for assistance! Once you've completed the
first 5 problems and all tests are passing, you can move onto the 6th bonus
problem.

We know you've got this!

________________________________________________________________________________
# Debugging A Stack Overflow

Uh oh! We've written a recursive function, but it's throwing an error!
Investigate the included problem and see if you can figure out what's going on.

Once you think you've fixed the issue, use `mocha` to confirm. Make sure
you're in the project's root: you should be in the same place as the `problems/`
and `test/` directories. Once there, run the following command:

```sh
> mocha
```

If you get stuck, step back and try breaking the problem down. Are we missing
any key steps for a recursive function?

When the tests pass and the error is gone, take a minute to celebrate - you're
officially a recursion debugger!

________________________________________________________________________________
# WEEK-03 DAY-5
*JS Trivia* {ignore=true}
________________________________________________________________________________
# JS Trivia Learning Objectives

Below is a complete list of the terminal learning objectives for this lesson.
When you complete this lesson, you should be able to perform each of the
following objectives. These objectives capture how you may be evaluated on the
assessment for this lesson.

1. Given a code snippet of a unassigned variable, predict its value.
2. Explain why functions are “First Class Objects” in JavaScript
3. Define what IIFEs are and explain their use case
4. (Whiteboarding) Implement a closure
5. Identify JavaScript’s falsey values
6. Interpolate a string using back-ticks
7. Identify that object keys are strings or symbols
8. A primitive type is data that is not an object and therefore cannot have
   methods(functions that belong to them).
9. Given a code snippet where variable and function hoisting occurs, identify
   the return value of a function learning objectives for this lesson.
When you complete this lesson, you should be able to perform each of the
following objectives. These objectives capture how you may be evaluated on the
assessment for this lesson.

1. Given a code snippet of a unassigned variable, predict its value.
2. Explain why functions are “First Class Objects” in JavaScript
3. Define what IIFEs are and explain their use case
4. (Whiteboarding) Implement a closure
5. Identify JavaScript’s falsey values
6. Interpolate a string using back-ticks
7. Identify that object keys are strings or symbols
8. A primitive type is data that is not an object and therefore cannot have
   methods(functions that belong to them).
9. Given a code snippet where variable and function hoisting occurs, identify
   the return value of a function.
________________________________________________________________________________
# Stop Feeling Iffy about IIFEs!

It's time to learn about some built in JavaScript functionality that will allow
you to define an anonymous function and then immediately run that function as
soon as it has been defined. In JavaScript we call this an Immediately-Invoked
Function Expression or IIFE (pronounced as “iffy”).

When you finish this reading you should be able to identify an
Immediately-Invoked Function Expression, as well as write your own.

## Quick review of function expressions

Before we get started talking about IIFEs lets quickly do a review of the syntax
anonymous function expressions.

A function expression is when you define a function and assign that function to
a variable:

```js
// here we are assigning a named function declaration to a variable
const sayHi = function sayHello() {
  console.log("Hello, World!");
};

sayHi(); // prints "Hello, World!"
```

We can also use function expression syntax to assign variables to anonymous
functions effectively giving them names:

```js
// here we are assigning an anonymous function declaration to a variable
const sayHi = function() {
  console.log("Hello, World!");
};

sayHi(); // prints "Hello, World!"
```

Now what if we only ever wanted to invoke the above anonymous function once? We
didn't want to assign it a name? To do that we can define an Immediately-Invoked
Function Expression.

## IIFE syntax

An _Immediately-Invoked Function Expression_ is a function that is called
immediately after it had been defined. The typical syntax we use to write an
IIFE is to start by writing an anonymous function and then wrapping that
function with the grouping operator, `( )`. After the anonymous function is
wrapped in parenthesis you simply add another pair of closed parenthesis to
invoke your function.

Here is the syntax as described:

```js
// 1. wrap the anonymous function in the grouping operator
// 2. invoke the function!
(function() {
  statements;
})();
```

Let's take a look at an example. The below function will be invoked right after
it has been defined:

```javascript
(function() {
  console.log("run me immediately!");
})(); // => 'run me immediately!'
```

Our above function will be defined, invoked, and then will _never be invoked
again_. What we are doing with the above syntax is forcing JavaScript to run our
function as a **function expression** and then to invoke that function
expression immediately.

Since an Immediately-Invoked Function Expression is _immediately invoked_
attempting to assign an IIFE to a variable will return the value of the invoked
function.

Here is an example:

```js
let result = (function() {
  return "party!";
})();

console.log(result); // prints "party!"
```

So we can use IIFEs to run an anonymous function immediately and we can still
hold onto the result of that function by assigning the IIFE to a variable.

## IIFEs keep functions and variables private

Using IIFEs ensures our global namespace remains unpolluted by a ton of function
or variable names we don't intend to reuse. IIFEs can additionally protect
global variables to ensure they can't ever be read or overwritten by our
program. In short using an IIFE is a way of protecting not only the variables
within a function, but the function itself. Let's explore how IIFEs do this.

When learning about scope we talked about how an outer scope does not have
access to an inner scope's variables:

```js
function nameGen() {
  const bName = "Barry";
  console.log(bName);
}

// we can not reference the bName variable from this outer scope
console.log(bName);
console.log(nameGen()); // prints "Barry"
```

Now what if we didn't want our outer scope to be able to access our function at
all? Say we wanted our `nameGen` function to only be invoked once and not ever
be invoked again or even to be accessible by our application again? This is
where IIFEs come in to the rescue.

One of the main advantages gained by using an IIFE is the very fact that the
function cannot be invoked after the initial invocation. Meaning that no other
part of our program can ever access this function again.

Since we don't ever intend to invoke this function again - there is no point in
assigning a name to our function. Let's take a look at rewriting our nameGen
function using a sneaky IIFE:

```js
(function() {
  const bName = "Barry";
  console.log(bName);
})(); // prints "Barry"

// we still cannot reference the bName variable from this outer scope
// and now we have no hope of ever running the above function above again
console.log(bName);
```

## What you learned

How to identify an IIFE, as well as how to write one.

________________________________________________________________________________
# Interpolation in JavaScript

When working with the `String` primitive type in JavaScript, you've probably
noticed it is not always an easy experience adding in variables or working with
multi-line strings. In the ES6 edition of JavaScript one of the new features
that was introduced to help with this problem was the Template Literal. A
Template Literal is a new way to create a string literal that expands on the
syntax of the `String` primitive type allowing for interpolated expressions to
be inserted easily into strings.

When you finish this reading you should be able to interpolate a string using
template literals.

## Let's talk syntax

To create a template literal, instead of single quotes (`'`) or double quotes
(`"`) we use the grave character, also known as the backtick (`). Defining a new
string using a template literal is easy - we can simply use backticks to create
that new string:

```js
let apple = `apple`;
console.log(apple); // apple
```

The important thing to know is that a template literal is still a `String` -
just with some really nifty features! The real benefits of template literals
become more obvious when we start talking about interpolation.

### Interpolation using template literals

One of the main advantages we gain by using template literals is the ability to
_interpolate_ variables or expressions into strings. We do this by denoting the
values we'd like to interpolate by wrapping them within curly braces with a
dollar sign in front(`${}`). When your code is being run - the variables or
expressions wrapped within the `${}` will be evaluated and then will be replaced
with the value of that variable or expression.

Let's take a look at that syntax by looking at a simple example. Compare how
easy to read the following two functions are:

```js

function boringSayHello(name) => {
    console.log("Hello " + name + "!");
};

function templateSayHello(name) => {
    console.log(`Hello ${name}!`);
};

boringSayHello("Joe"); // prints "Hello Joe!"
templateSayHello("Joe"); // prints "Hello Joe!"
```

As we can see in the above example, the value of the variable is being
interpolated into the string that is being created using the template literal.
This makes our code easier to both write and read.

You'll most often be interpolating variables with template literals, however we
can also interpolate expressions. Here is an example of evaluating an expression
within a template literal:

```js
let string = `Let me tell you ${1 + 1} things!`;
console.log(string); // Let me tell you 2 things!
```

### Multi-line strings using template literals

We can also use template literals to create multi-line strings! Previously we'd
write multi-line strings by doing something like this:

```js
console.log("I am an example\n" + "of an extremely long string");
```

Using template literals this becomes even easier:

```js
console.log(`I am an example
of an extremely long string
on multiple lines`);
```

## What you learned

How to use template literals to interpolate values into a string.

________________________________________________________________________________
# Object Keys in JavaScript

As we previously covered, the Object type in JavaScript is a data structure that
stores key value pairs. An object's `values` can be anything: Booleans,
Functions, other Objects, etc. Up to this point we have been using strings as
our object `keys`. However, as of ES6 edition of JS we can use another data type
to create Object keys: `Symbols`.

In this reading we'll be talking about the `Symbol` primitive data type and how
an object's keys can be either a `String` _or_ a `Symbol`.

## A symbol of unique freedom

The main advantage of using the immutable `Symbol` primitive data type is that
each `Symbol` value is **unique**. Once a symbol has been created it **cannot**
be recreated.

Let's look at the syntax used to create a new symbol:

```js
// the description is an optional string used for debugging
Symbol([description]);
```

To create a new symbol you call the `Symbol()` function which will return a new
unique symbol:

```js
const sym1 = Symbol();

console.log(sym1); // Symbol()
```

Here is an example of how each created symbol is guaranteed to be **unique**:

```js
const sym1 = Symbol();
const sym2 = Symbol();

console.log(sym1 === sym2); // false
```

You can additionally pass in an optional `description` string that will allow
for easier debugging by giving you an identifier for the symbol you are working
with:

```js
const symApple = Symbol("apple");
console.log(symApple); // Symbol(apple)
```

Don't confuse the optional `description` string as way to access the Symbol you
defining though - the string value isn't included in the Symbol in anyway. We
can invoke the `Symbol()` function multiple times with the same description
string and each newly returned symbol will be unique:

```js
const symApple1 = Symbol("apple");
const symApple2 = Symbol("apple");

console.log(symApple1); // Symbol(apple)
console.log(symApple2); // Symbol(apple)
console.log(symApple1 === symApple2); // false
Symbol("foo") === Symbol("foo"); // returns false
```

Now that we've learned how to define symbols and that symbols are unique it's
time to talk about _why_ you would use a symbol. The main way the `Symbol`
primitive data type is used in JavaScript is to create unique object keys.

## Symbols vs. Strings as keys in Objects

Before the ES6 edition of JavaScript Object keys were exclusively strings. We
could you either dot or bracket notation to set or access an object's string
key's value.

Here is a brief refresher on that syntax:

```js
const dog = {};
dog["sound"] = "woof";
dog.age = 4;
// using bracket notation with a variable
const col = "color";
dog[col] = "grey";

console.log(dog); // { sound: 'woof', age: 4, color: 'grey' }
```

One of the problems with using strings as object keys is that in the Object type
each key is _unique_. Meaning that sometimes we could inadvertently overwrite a
key's value if we mistakenly try to reassign the same key name twice:

```js
const dog = {};
// I set an 'id' key value pair on my dog
dog["id"] = 39;

// Here imagine someone else comes into my code base and
// accidentally adds another key with the same name!
dog.id = 42;

console.log(dog); //  { id: 42 }
```

When a computer program attempts to use the same variable name twice for
different values we call this a _name collision_. While the above code snippet
is a contrived example, it is a good demonstration of a common issue. Further on
in this course you'll find yourself installing many code libraries (like the
`mocha` test library) for each project you work on. The more libraries that are
imported into a single application the greater the chance of a name collision.

I bet you are sensing a _unique_ theme by now. Using `Symbols` as your object
keys is a great way to prevent name collision on objects because Symbols are
_unique_!

Let take a took at how we could fix the above code snippet using symbols:

```js
const dog = {};
const dogId = Symbol("id");
dog[dogId] = 39;

const secondDogId = Symbol("id");
dog[secondDogId] = 42;

console.log(dog[dogId]); //  39
console.log(dog); //  { [Symbol(id)]: 39, [Symbol(id)]: 42 }
```

Note above that we can access our key value pair using bracket notation and
passing in the variable we assigned our symbol to (in this case `dogId`).

### Iterating through objects with symbol keys

One of the other ways that `Symbols` differ from `String` keys in an object is
the way we iterate through an object. Since `Symbols` are relatively new to
JavaScript older Object iteration methods don't know about them.

This includes using `for...each` and `Object.keys()`:

```js
const name = Symbol("name");
const dog = {
  age: 29
};
dog[name] = "Fido";

console.log(dog); // { age: 29, [Symbol(name)]: 'Fido' }

console.log(Object.keys(dog)); // prints ["age"]

for (let key in dog) {
  console.log(key);
} // prints age
```

This provides an additional bonus to using symbols as object keys because your
symbol keys that much more hidden (and safe) if they aren't accessible via the
normal object iteration methods.

If we do want to access all the symbols in an object we can use the built in
`Object.getOwnPropertySymbols()`. Let's take a look at that:

```js
const name = Symbol("name");
const dog = {
  age: 29,
  // when defining an object we can use square brackets within an object to
  // interpolate a variable key
  [name]: "Fido"
};

Object.getOwnPropertySymbols(dog); // prints [Symbol(name)];
```

Using symbols as object keys has some advantages in your local code but they
become really beneficial when dealing with importing larger libraries of code
into your own projects. The more code imported into one place means the more
variables floating around which leads to a greater chance of a name collisions -
which can lead to some really devious debugging.

## What you learned

There are two primitive data types that can be used to create keys on an Object
in JavaScript: `Strings` and `Symbols`. The main advantage to using a `Symbol`
as an object's key is that Symbols are guaranteed to be **unique**.

________________________________________________________________________________
## Primitive Data Types in Depth

It's time to dive deeper into the world of JavaScript data types! Previously, we
learned about the difference between the Primitive and Reference data types. The
main difference we covered between the two data types is that primitive types
are immutable, meaning they cannot change. It's now time to dive a little deeper
into this subject and talk about how primitive data types are not just immutable
in terms of reassignment - and also because we are not able to define new
methods on primitive data types in JavaScript.

At the end of this reading you you be able to identify why primitive types do
not have methods.

## Data types in JavaScript

With the JavaScript ECMAScript 2015 release, there are now eight different data
types in JavaScript. There are seven primitive types and one reference type.

Below we have listed JS data types along with a brief description of each type.

**Primitive Types**:

1. `Boolean` - `true` and `false`
2. `Null` - represents the intentional absence of value.
3. `Undefined` - default return value for many things in JavaScript.
4. `Number` - like the numbers we usually use (`15`, `4`, `42`)
5. `String` - ordered collection of characters ('apple')
6. `Symbol` - new to ES5 a symbol is a _unique_ primitive value
7. `BigInt` - a data type that can represent larger integers than the `Number`
   type can safely handle.

**One Reference Type**:

1.  `Object` - a collection of properties and methods

As we have previously discussed one of the main differences between primitive
and reference data types in JavaScript is that primitive data types are
**immutable**, meaning that they cannot be changed. The other main thing that
sets primitives apart is that primitive data types are not Objects and therefore
_do not have methods_.

## Methods and the object type

When we first learned about the Object data type we learned about the definition
of a _method_. As a reminder, the definition of a method is a function that
belongs to an object.

Here is a simple example:

```js
const corgi = {
  name: "Ein",
  func: function() {
    console.log("This is a method!");
  }
};

corgi.func(); // prints "This is a method!"
```

The Object type is the only data type in JavaScript that has methods. **Meaning
that primitive data types cannot have methods.** That's right - we cannot
declare new methods or use any methods on JavaScript primitive data types
because they are Objects.

For example when finding the square root of a number in JavaScript we would do
the following:

```js
// This works because we are calling the Math object's method sqrt
let num = Math.sqrt(25); // 5

// This will NOT work because the Number primitive has NO METHODS
let num = 25.sqrt; // SyntaxError: Invalid or unexpected token
```

The `Number` primitive data type above (`25`) does not have a `sqrt` method
because only Objects in JavaScript can have methods. To sum up the previous
sections: Primitive data types are **not** Objects therefore they do not have
methods.

## Primitives with object wrappers

Right now you might be thinking - wait a second what about the string type?
After all, we can call `String#toUpperCase` on an instance of a string? Well
that is because of how the string type is implemented in JavaScript.

The underlying primitive data type of `String` does not have methods. However,
to make the String data type easier to work with in JavaScript it is implemented
using a `String` object that _wraps_ around the `String` primitive data type.
This means that the `String` object will be responsible for constructing new
`String` primitive data types as well as allowing us to call methods upon it
because it is an Object.

We'll be diving a lot more into this concept when we get to JavaScript Classes
but for brevity's sake we are going to do a walkthough of the code snippet below
to clarify the difference between the `String` primitive type, and the `String`
object that wraps around it:

```js
let str1 = "apple";

str1.toUpperCase(); // returns APPLE

let str2 = str1.toUpperCase();

console.log(str1); //prints apple
console.log(str2); //prints APPLE
```

So in the above example when we call `str1.toUpperCase()` we are calling that on
the `String` object that wraps around the `String` primitive type.

This is why in the above example when we `console.log` both `str1` and `str2` we
can see they are different. The value of `str1` has not changed because it
can't - the `String` primitive type is _immutable_. The `str2` variable calls
the `String#toUpperCase` method on the `String` object which wraps around the
`String` primitive. This method cannot mutate the `String` primitive type
itself - it can only point to a new place in memory where the `String` primitive
for `APPLE` lives. This is why even though we call `str1.toUpperCase()` multiple
times the value of that variable will never change until we reassign it.

Don't worry if this is confusing at first, as we dive more into JavaScript
you'll learn more about how JavaScript implements different types of Objects to
try and make writing code as clear as possible.

## What you learned

The important takeaway here is that primitive data types in JavaScript are not
objects and therefore cannot have methods.

________________________________________________________________________________
# Unassigned Variables in JavaScript

Up this point we've covered a lot of of information about the different ways to
declare a variable in JavaScript. This reading is going to center in on a topic
we've touched on but haven't gone over in great detail: what is the value of a
declared variable with no assigned value?

By the end of this reading you should be able to look at a code snippet and
predict the value of any declared variable that is not assigned a value.

## The default value of variables

Whenever you declare a `let` or `var` variable in JavaScript that variable will
have a _name_ and a _value_. That is true of `let` or `var` variables with no
assigned value either! When declaring a variable using `let` or `var` we can
optionally assign a value to that variable.

Let's take a look at an example of declaring a variable with `var`:

```js
var hello;
console.log(hello); // prints undefined
```

So when we declare a variable using `var` the default value assigned to that
variable will be `undefined` if no value is assigned.

The same is true of declaring a variable using `let`. When declaring a variable
using `let` we can also choose to optionally assign a value:

```js
let goodbye;
console.log(goodbye); // prints undefined
```

However, this is a case where `let` and `const` variables differ. When declaring
a variable with `const` we must provide a value for that variable to be assigned
to.

```js
const goodbye;
console.log(goodbye); // SyntaxError: Missing initializer in const declaration
```

This behavior makes sense because a `const` variable cannot be reassigned -
meaning that is we don't assign a value when a `const` variable is declared we'd
never be able to assign a new value!

So the default assigned value of a variable declared using `var` or `let` is
`undefined`, whereas variables declared using `const` need to be assigned a
value.

## The difference between default values and hoisting

When talking about default values for variables we should also make sure to
underline the distinction between _hoisting_ variable names and default values.

Let's look at an example:

```js
function hoistBuddy() {
  var hello;
  console.log(hello); // prints undefined
}

hoistBuddy();
```

Whenever a variable is declared with `var` that variable's name is hoisted to
the top of its declared scope with a value of `undefined` until a value is
assigned to that variable name. If we never assign a value to the declared
variable name then the default value of a `var` declared variable is
`undefined`.

Now let's take a look at the example above but this time using `let`:

```js
function hoistBuddy() {
  let hello;
  console.log(hello); // prints undefined
}

hoistBuddy();
```

The default value of a `let` declared variable is `undefined`. However, don't
confuse this with how a `let` defined variable is hoisted. When a `let` variable
is declared the name of that variable is hoisted to the top of its declared
scope and if a line of code attempts to interact with that variable before it
has been assigned a value an error is thrown.

The following example shows the difference in **hoisting** between `var` and
`let` declared variables:

```js
function hoistBuddy() {
  console.log(hello); // prints undefined
  var hello;

  console.log(goodbye); // ReferenceError: Cannot access 'goodbye' before initialization
  let goodbye;
}

hoistBuddy();
```

## What you learned

The default value of a variable assigned with either `let` or `var` is
`undefined`. Variables declared using `const` need to have an assigned value
upon declaration to be valid.

________________________________________________________________________________
# WhiteBoarding Problem

## The Question

Write a function named `dynamicDivider(divisor)`. When invoked the
`dynamicDivider` function will intake a number to be used as a divisor and will
then return a new function. The function returned by `dynamicDivider` will
accept a number - and that number will then be divided by the `divisor` that was
defined when the `dynamicDivider` was first invoked.

Examples:

```js
let halvedbyTwo = dynamicDivider(2); //returns a function
halvedbyTwo(12); // returns 6
halvedbyTwo(18); // returns 9

let halvedbyThree = dynamicDivider(3); // returns a function
halvedbyThree(12); // returns 4
halvedbyThree(18); // returns 6
```

## The Answer

```js
function dynamicDivider(divisor) {
  // here we are returning an inner function that will create a closure by
  // closing over and accessing the above divisor argument to use within the
  // function returned below

  return function(num) {
    return num / divisor;
  };
}
```


text:
## Portfolio

---

### Data Dashboard

[World Bank Data Dashboard - Exploring Top 10 Economies Land use](/https://udacity-worldbank-dboard034x.herokuapp.com)

### Data Analysis
---
[Gender based vilence: How Kenya compares to the rest of the World](https://medium.com/analytics-vidhya/gender-based-violence-how-kenya-compares-with-the-rest-of-the-world-12cf08118d50/)

---

### Links to the Projects

- [World Bank Data Dashboard](https://udacity-worldbank-dboard034x.herokuapp.com/)
- [Gender based violence: How Kenya Compares to the rest of the world](https://medium.com/analytics-vidhya/gender-based-violence-how-kenya-compares-with-the-rest-of-the-world-12cf08118d50/)
- [Data Cleaning articles](https://3liud.medium.com/a-data-cleaning-journey-2b0146407e44/)
- [Project 4 Title](http://example.com/)
- [Project 5 Title](http://example.com/)

---

---

Eliud Njoki Portfolio © 2021

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# Web typography

- Emma Younan | VID1

## Closed captions - The assignment

During the Visual Interface Design minor, we had a Web Typography course. In this course we had to design a tailor-made closed captions experience for a deaf user. How to enhance the film-watching experience and how to visualize different sounds. We had to design the closed captions for two scenes from the Blade Runner 2049 movie. The whole film watching experience disappears when it is not clearly indicated who is talking or what music is playing in the background. These two things and much more creates different emotions when watching a film. So without it you will miss what a scene is about.

For this kind of assignments it is really important to know your user's identity, the identity of the product (film), and your own identity. Making a combination of those three will help you bring all those identities back into your design. And that will help you be more creative and think about designs that are different from your own style.

## Know the identity

### The Blade Runner film - Identity

I have watched the Blade Runner 2049 movie before this course. And I found it and still find it not that strong in terms of content. If you just read the subtitles without having the sound on, you will find that the conversations are not always that interesting. But the sound effects used in the background are what make it exciting to watch. The entire film is about building tension and setting dark atmospheres.

### Getting to know the user - Darice - Identity

To get to know Darice a little better, I had a small conversation with her. To ask about her preferences and her daily life, but also to know more about her experience with watching movies.
Darice is a front-end developer that likes Netflix, books, writing (blog), cooking, and photography. She likes minimalistic designs with a touch of an accent color (neons).

- According to Darice, watching a movie is exciting when the sounds are clearly indicated. It is not enough to just have a text that says [music]. Oke, but what kind of music is it?

- For her Readability is very important. So having a readable color for the closed captions is crucial. Paying attention to the contrast between the background and the text will help to improve the readability of the text.

- Consistency is very important for Darice when it comes to closed captions. For example when using colors to indicate a character, a type of sound, etc., you have to be consistent by using the same color for the same character all the time. In this way, Darice can recognize the character without having to read the character's name. So the color becomes the character's identity for Darice.

- When having a background song, Darice would like to have the lyrics shown in the closed captions instead of having [music].

- One more important insight that I got from the conversation with Darice. Is that it is very important to indicate who or what is making the noise, when the noise is not clearly visible on the screen.

- Darice is also very used to a few standard rules within closed captions. Like indicating the background music sound between two brackets [..].

### My own identity

I would describe myself to be someone that likes to design with originality in mind. For example adding elements or small details to the design that you wouldn't normally think about. It makes the design more exciting and interesting. I really like animations and moving objects. I have a thing for retro designs. And sometimes I create just crazy things, kipping in mind why I am designing this and for whom.

## Design decisions based on the identities/ test sessions

After talking to Darice, watching the Blade Runner film, and thinking about what I want to do. I started by creating two categories to design for (Typography and Sound animation, and a color use description within these two categories).

### Typography

Knowing that readability for Darice is very important, distraction in the text is annoying, her preference for minimal design while having the important moments designed in a clear way. For example when the emphasis is placed on something, you can indicate that by different font weights. That is why I decided to use the Brenner font family and because of the many possibilities that this font family has it will be much easier and more efficient when designing the closed captions. Using the Brenner font family will give me more options to experiment with typography than choosing to work with the system fonts. Not all system fonts are easy to read as subtitles, and moreover I find the Brenner family mush better to use as typography for this film because of the many styles that this font family has, opening the opportunity to choose a font that matches in characteristics with a sound or a character in the two Blade Runner scenes.

**Typography - First version**

In my first version, I used Brenner sans for the subtitles for all characters with different font-weight for each character to make it more clear who is talking at a particular moment.

Another thing that I did with the text is that I positioned the text of the different characters, one at the left side of the screen (the voice talking to officer K), and officer K text at the right side of the screen to make it look like a conversation message between the two. The position of the two character text is based on the scene where officer K is talking through a machine with the person that is testing him.

I also had a bolder font weight for the angry man to indicate that the man was angry and talking in a mean way.

**Color use for typography - First version**

Having a black background will set the intense mood for the film and the typography used for the closed captions.
Based on what the movie style is. Dark, intense, futuristic having lots of lights neon colors blacks and greys. And knowing that Darice likes neon colors. I used a bright blue color for the voice talking through the machine. And a simple white color for the character (officer K), this character is the main character with the most text lines. And because Darice is mostly used to read white text as subtitles, I chose to use a simple white. I also used a red color for the angry man text to indicate his anger.

**Feedback Darice - Typography -  First version**

- Darice found positioning the text didn’t give a clear view of who was talking at the moment.
- Not having the names of the characters within the text in the first version made Darice a little bit confused about who is talking at a particular moment. She would find it more helpful to have a name indication for the characters.
- When using an icon instead of the name of the characters, Darice would like to have a description of the icon - what does each icon mean.
- To have more clarity between the different characters, she would find it more efficient if I used a different font style for each character. While keeping consistency and readability in mind.
- Darice would also like to have a text by each of the background sounds, to make the sound animation more clear.
- Color use in the typography was clear.
- The last sentence from the first scene is repeated three times by officer K, Darice would like to have that text designed in a way that shows that the sentence is being repeated.

 ***

**Typography - Second version**

After the first feedback session with Darice. I made a couple of changes and started working on my second version.

For the second version of the closed caption typography. I used three different font styles from the Brenner font family. Each character now has its own font style.

The subtitles for officer K, is Brenner sans with a font weight of 250. I decided to have a lighter weight text for officer K to make it match more with how he speaks (in a low neutral tone).

For the voice talking to officer K, I decided to use Brenner mono with a font weight of 400. Giving a mono type to this character will help Darice to understand that this is a voice of someone that is coming from a machine. Mono types are associated with robots and electronics and that is something that Darice also knows. The decision to make this text bolder came from the tone of voice that this person has and its characteristics (mainly being louder and more confident).

The text for the angry man has now a Brenner Regular Italic. I find that this font style works with the angry and mean characteristics of this character. The man is not being angry in a loud way but he is angry in a very mean way.

The text for this version is positioned in the center. From the first feedback Darice found the text positions difficult to read and not clear why the text of different characters is coming from different sides.

To make it more clear for Darice which one of the characters is talking. I designed a small label that indicates whether officer K is talking or the other voices.

And to make the sound animation more understandable. I added extra description text by each background sound. Using the  Brenner Display font style in a grey color. To separate this text from the main subtitles text.

The last thing that I did for this version, was making it clear that the last sentence from the first scene was repeated three times. I decided to use animation for that. By making the text appear three times.

**Feedback Darice - Typography - Second version**

In the second feedback session, Darice had some tips and tops to give the design.

- As a tip, the color used for the sound description text was not really readable for her. That is because of the use of the grey color for that text. She would like a color that has more contrast with the background all the time.
- As for tops, She found that the use of description text by the background sounds very helpful and clear. The subtitle text is readable and it is more clear who is talking now. And she also found that it is now obvious that the last sentence from the first scene is repeated 3 times.

### Sound animation

Background sounds play a huge role in setting the mood of the movie and of the watcher.

**Sound animation - First version**

By making use of the overlapping blue circles I tried to visualize the background sounds as multiple sound waves. The larger the circles, the louder the sound. The speed of the circle's animation indicates how fast the sound is. I chose circles to animate behind the iframe because it goes well with the style of the movie, The bare style of brutalist design building with neon lights that comes almost in each scene. Another reason for using the only one shape (circle) that changes slightly in the form to visualize the sounds, is that Darice likes minimalism in design. So I wanted to create a simple animation that slightly changes through the sounds, to be a background animation for the movie that is consistent and doesn't distract Darice from the movie.

**Color use in sound animation - First version**

For the continuous background music, I chose to use light blue colors that represent the sound waves. Brighter the blue, higher the sound tone. And the color blue goes well with the movie vibes.

For high tone sounds, I chose a white color. Because white is a pure color that has a high contrast with the black in the background.

The red circles appear when a buzzer alarm sound is invoked. I chose red because it is recognizable that the alarm lights are red. So I used it as a pattern for my design.

**Feedback Darice - Sound animation - First version**

- Since the circle animation is not a direct indication of what object is making the sound, it was difficult for Darice to properly understand the sound animation.

- Using different colors for the circles works good to indicate to different sounds.

***

**Sound animation - Second version**

For the second feedback session with Darice I wanted to test the circle animation one more time but supported with a description text. To see if this animation sets the right mood for Darice when supported with a description text.

I used a medium grey color for the supporting sound text.

**Feedback Darice - Sound animation - First version**

- Darice found that the animation is setting the right mood. And the supporting text makes the animation more understandable for her.
- She found the supporting text color to have a low contrast with the background which makes it hard to read.
- She was interested in the animation and curious about what the latest version will be.

## The last version - Blade Runner closed captions

### Typography

**What I already had in the previous versions**

Three different font styles from the Brenner font family. Each character now has its own font style. Officer K (Brenner sans - 250), The voice talking to officer K (Brenner mono - 400), and the angry man (Brenner Regular Italic).
The text for is positioned in the center.

Small labels by the subtitles  that indicate which character is talking.

Grey description text by each background sound (Brenner Display).

Last sentence of the first scene animated to visualise that the sentence is repeated 3 times.

**What did I change after the second feedback from Darice**

I changed the description text color to a hot pink Color to make the style of the sound description text other than the main subtitles text. I did that to make it more readable for Darice, because she found it not really readable in the last test session.

### Sound animation

**What I already had in the previous versions**

Overlapping blue circles to visualize the background sounds as multiple sound waves. The larger the circles, the louder the sound. The speed of the circle's animation indicates how fast the sound is. Different circle color for different sounds.

**What did I change after the second feedback from Darice**

To help Darice to visualize the sounds more, I adjusted the iframe and slightly animated it to build up the sound animation by scaling the iframe. I also rotated the iframe when a sound had a vibration effect to it, to give the screen the effect that it is vibrating.

## Exclusive Design principles - Final version

### Study situation

At the beginning of the course I had a good conversation with Darice to get to know her a little bit better, to determine her identity, and to understand what she needs to have a great movie experience. To see what she likes better and what she prefers. And to start thinking about solutions to those problems that she has with the currently closed captions. What I found out is that Darice likes action movies because they have lots of visual effects that can describe the vibe of the movie without having to hear the background sounds and music. For the non-action movies this effect can be created in the closed captions section. A simple text or shape animation to visualize the background sounds the same way the visual effects do in action movies.

### Ignore conventions

I tried to create a completely different experience by ignoring the subtitle design rules. I gave the character names a designed label and didn't use brackets [...] to display the names. I also used movement and animation on the video iframe. To create the vibration feeling some sounds have, and the high and the low notes. Used circle forms to indicate to the sound waves. By using extra scale and shake movments on the iframe I ignored my own convention of wanting to have one shape form for the background sound animation.

### Prioritize identity

By studying the situation and the user (Darice) and also looking at my own identity and the identity of the Blade Runner movie. I mapped out the most important insights that I can use to create a project that combines those three identities. You can find through this documentation when did I use those identities and how.

### Add nonsense

Having the chance to create whatever you want and be creative as much as you want and experimenting with new fields of design opportunities. Makes adding nonsense really fun. Adding a background animation to a movie is nonsense that could really work in designing for deaf audio. Creating a vibration effect for the iframe is also nonsense. Just ask yourself how many movies use this kind of effect to visualize sounds for those who can not hear it, then you will know why they will think that this is nonsense. Because it is not been done yet and it seems that no one is interested in experimenting with new things. Adding nonsense can lead you to new cool ideas, which you have never could think about. It helps you think out of the box.

## Author

- Emma Younan

license: MIT


text:
WMI_INST
============

Deploy windows 2003 server additional component 'wmi windows installer provider'

Documentation
-------------

This state will help you to deploy optional windows component "wmi windows
installer provider" with salt.

You need it on windows server 2003 otherwise, salt-minion can't report complete
list of installed softwares.

To use this state you need to put 3 files from windows 2003 install CD to i386
folder:

* MSI.MF_
* MSI.MO_
* MSIPROV.DL_

repository: saltstack/salt-winrepo-ng

gha_language: SaltStack

gha_license_id: NOASSERTION

repo_name: saltstack/salt-winrepo-ng


text:
# Dwayalomella setulosa Carris, 1989 SPECIES

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 81(4): 638 (1989)

#### Original name
Dwayalomella setulosa Carris, 1989

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
---
title: 'Coronavirus: Whanganui principals reassure community with precautions'
feature_image:
  credit: Supplied
  description: >-
    The Ministry of Health and Ministry of Education have put in place
    guidelines for schools on the health of their students and staff.
  image: >-
    https://res.cloudinary.com/whanganuihigh/image/upload/v1580778342/News/Chron_30.1.20.jpg
news_author:
  date: 2020-01-30T01:01:54.964Z
  name: Lucy Drake
  publication: Whanganui Chronicle
image_gallery:
  - description: >-
      Coronavirus has so far infected 2700 people and killed at least 81
      worldwide. Photo / Supplied.
    image: >-
      https://res.cloudinary.com/whanganuihigh/image/upload/v1580778376/News/photo_of_man_with_mask._chron_30.1.20.jpg
  - description: >-
      Whanganui High School principal Martin McAllen said they will closely
      monitor the health of their international students. Photo / Bevan Conley.
    image: >-
      https://res.cloudinary.com/whanganuihigh/image/upload/v1580778413/News/Martin_McAllen_Chron_30.1.20.jpg
show_in_slider: false
date: 2020-02-04T01:01:54.986Z
---
As international students travelling from areas affected by coronavirus prepare to touch down Whanganui, secondary school principals are advising the community there is no need to be alarmed.

Whanganui High School principal Martin McAllen has informed his school that its international department has students who have arrived, or are about to arrive, from countries that have small numbers of people who have contracted the virus.

"We are following guidelines from the ministries of education and health with regards to the health of our students and staff and we are ready to adapt our precautions if the seriousness of the situation develops further."

He said he was very happy with the robust precautions that have been put in place by the school's international team and they would continue to monitor closely the health of international students.

"We are ready to adapt our precautions if the seriousness of the situation develops further."

McAllen has been advised by the Whanganui District Health Board that most cases inside and outside China have been connected to Wuhan and high-risk exposure only applied to people who have been in Wuhan within the last 14 days.

Anyone else travelling from China should be aware of the symptoms but is not required to stay away from school unless they are sick, he said.

Whanganui Collegiate School headmaster Wayne Brown said families have been asked to advise the school if they have travelled to, or have visitors from, affected areas.

Brown said staff at the school's boarding houses, residential staff, health centre and international department are fully aware of the situation and will continue to work together.

New Zealand International Commercial Pilot Academy chief operating officer, Tania King, said they were expecting a number of Indian international students to arrive in Whanganui in February but no students from any of the high-risk areas in China.

"Obviously we do have a high number of international students that come through our academy and so we are just taking the advice from the Ministry of Health and have put in place precautionary measures," King said.

UCOL Whanganui campus manager Bronwyn Paul said they do not have any international students arriving at their campus from any affected areas.
Whanganui medical officer of health Patrick O'Connor said generally the whole country was on heightened alert but it was an alert rather than an alarm.

"There are cases outside Wuhan but the significant transmission of infection is mainly Wuhan so I'm a bit concerned that everyone is worried about travel from all of China and I think that's a little excessive at the moment."

The Ministry of Education urges anyone with a particular concern about the health of any child, student or staff member to contact Healthline on 0800 611 116 or their GP for medical advice.

gha_language: Blade

gha_license_id: MIT


text:
# PoshUSNJournal
A PowerShell module to manage and view the USN Journal

```PowerShell
Install-Module -Name PoshUSNJournal
```

repository: proxb/PoshUSNJournal

gha_language: PowerShell

repo_name: proxb/PoshUSNJournal


text:
# Change Log

All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

# [0.6.0](https://github.com/hyperledger/cactus/compare/v0.4.1...v0.6.0) (2021-07-19)

### Bug Fixes

* **connector-corda:** container image kotlin compilation fails in model ([a8a4531](https://github.com/hyperledger/cactus/commit/a8a4531d379fe16d4c991802525ec573a7e3ede1))
* **connector-xdai:** add missing hasTransactionFinality ([cc4f3e1](https://github.com/hyperledger/cactus/commit/cc4f3e141da9292b8db5b0261a3347b3ba9c0689))
* **connector-xdai:** web3.eth.estimateGas, works considering called solidity method do not throw an exception. So, for method having modifier with access control on msg.sender calling estimateGas without from field throws error.to make it work ,transactionConfig.from = web3SigningCredential.ethAccount before calling estimateGas ([63f5ff6](https://github.com/hyperledger/cactus/commit/63f5ff62b20aaf4dfdb5dd48a24dabc3342a0868))

### Features

* **connector-xdai:** add interval to pollForTxReceipt ([40be742](https://github.com/hyperledger/cactus/commit/40be74234f3bbd059fbc41f61890d25eec1d6ff8))
* **connector-xdai:** add ledger connector plugin for xdai [#852](https://github.com/hyperledger/cactus/issues/852) ([99399a3](https://github.com/hyperledger/cactus/commit/99399a3bd5020c66d2899aca500a880777b6523d))
* **core-api:** plugin async initializer method ([9678c2e](https://github.com/hyperledger/cactus/commit/9678c2e9288a73589e84f9fd254c26aed6a93297))

# [0.5.0](https://github.com/hyperledger/cactus/compare/v0.4.1...v0.5.0) (2021-05-19)

### Bug Fixes

* **connector-xdai:** add missing hasTransactionFinality ([cc4f3e1](https://github.com/hyperledger/cactus/commit/cc4f3e141da9292b8db5b0261a3347b3ba9c0689))

### Features

* **connector-xdai:** add ledger connector plugin for xdai [#852](https://github.com/hyperledger/cactus/issues/852) ([99399a3](https://github.com/hyperledger/cactus/commit/99399a3bd5020c66d2899aca500a880777b6523d))

repository: AYUDA-SOLUTION/cactus

branch_name: refs/heads/main

repo_name: AYUDA-SOLUTION/cactus


text:
# Durable Function Support

This is a library to make testing Azure [Durable Functions](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview) easier.

The library was extracted from a utility class and could use some clean-up.

## Await a Durable Function

Many of our durable orchestrators are triggered by a "normal" Azure function (e.g., HTTP-triggered or queue-triggered).  In our automated acceptance tests, we've struggled to balance keeping the test runtime short against making sure the test will pass.  This is especially challenging when we move past local development to another environment (e.g., Jenkins, Azure DevOps, GitHub Actions) where tests might run longer.  In a pattern like this...

```csharp
var response = await client.SendAsync(httpTriggerFunctionRequest);  // Trigger the function that starts the orchestrator
Thread.Sleep(15000);
// Assume the orchestrator had time to complete; continue with an assertion or next step
```

...we have found ourselves repeatedly bumping up `Sleep` times to get the tests to pass more reliably.  But 10 seconds times 10 tests adds almost two minutes per test run.  That certainly adds up.

The `Awaiter` (via the `DurableFunctionClient`) uses the [Durable Function API](https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-http-api) to check status.

(Note:  As of now, the `DurableFunctionClient` assumes you are using the Azure function emulator to [run functions locally](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local#start), with a `localhost` URL.)

```csharp
var client = new DurableFunctionClient(portNumber);  // Typically 7071
client.PurgeInstanceHistoriesAsync();  // Not strictly needed, but keeps tests from interfering with each other

var response = await client.SendAsync(httpTriggerFunctionRequest);  // Trigger the function that starts the orchestrator

var instanceId = await Awaiter.WaitForFunction(client)
// When the awaiter returns, it has either timed out or the durable function is done running
```

Specific instances can be awaited using `WaitForInstance`, or orchestrators with a particular name can be awaited using `WaitForInstanceByName`.


text:
# terraform-kubernetes-jenkins

Terraform module for deploying Jenkins on Kubernetes

## Usage

```terraform
module "this" {
  source              = "github.com/jjno91/terraform-kubernetes-jenkins?ref=master"
  jenkins_volume_id   = "vol-abc123"
  jenkins_volume_size = "50"
}
```

## Configuring Kubernetes Cloud

Jenkins will be accessible inside the Kubernetes cluster from the DNS <identifier>.<identifier>.svc.cluster.local

This DNS will need to be entered in the "Jenkins URL" config field for Kubernetes Cloud definition in order for K8S based JNLP agents to reach Jenkins

<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|:----:|:-----:|:-----:|
| identifier | (optional) Used to generate namespace and name resources | string | `"jenkins"` | no |
| jenkins\_image | Jenkins container image | string | `"jenkins/jenkins:latest"` | no |
| jenkins\_version | (optional) https://hub.docker.com/r/jenkins/jenkins/tags | string | `"latest"` | no |
| jenkins\_volume\_id | (required) Jenkins persists its data on disk and needs a static EBS volume ID in order to maintain state | string | `""` | no |
| jenkins\_volume\_size | (required) Jenkins volume size in gigabytes | string | `""` | no |
| jnlp\_node\_port | (optional) JNLP port used by Jenkins agents | string | `"30001"` | no |
| jnlp\_port | (optional) JNLP port used by Jenkins agents | string | `"50000"` | no |
| labels | (optional) Additional labels applied to all resources | list | `[]` | no |
| volume\_availability\_zone | (required) Jenkins must be deployed to the same zone as its persistent data volume | string | `""` | no |
| web\_node\_port | (optional) Jenkins web port internal to the Jenkins container | string | `"30000"` | no |
| web\_port | (optional) Jenkins web port internal to the Jenkins container | string | `"8080"` | no |

<!-- END OF PRE-COMMIT-TERRAFORM DOCS HOOK -->

license: Unlicense

repository: awsiv/terraform-kubernetes-jenkins

repo_name: awsiv/terraform-kubernetes-jenkins