diff --git a/.images/github_commits.png b/.images/github_commits.png new file mode 100644 index 0000000..76418f4 Binary files /dev/null and b/.images/github_commits.png differ diff --git a/02 JavaScript Objects.md b/02 JavaScript Objects.md index d5a807b..54c9479 100644 --- a/02 JavaScript Objects.md +++ b/02 JavaScript Objects.md @@ -232,7 +232,7 @@ Generally, object literals are more concise and easier to read. They also run fa ### 2.4 Test Your Knowledge -TODO +TODO: Constructor example ## 3 The Function Object diff --git a/03 Asynchronous JavaScript.md b/03 Asynchronous JavaScript.md index ce3625f..7cd8cae 100644 --- a/03 Asynchronous JavaScript.md +++ b/03 Asynchronous JavaScript.md @@ -190,9 +190,90 @@ The sample script `generators.js` has the same functionality as the previous scr _A promise is an object that proxies for the return value thrown by a function that has to do some asynchronous processing (Kris Kowal)._ -The key component is the `.then()` method which is how we get the resolved (or fulfilled) value or the exception it has thrown. +A promise represents the result of an asynchronous operation. As such it can be in one of three possible states: -### 6.1 Test Your Knowledge +1. pending - the initial state of a promise. +2. fulfilled - the asynchronous operation was successful. +3. rejected - the asynchronous operation failed. + +### 6.1 Creating a Promise + +Promises are created using the `new` keyword. This function is called immediately with two arguments. The first argument resolves the promise and the second one rejects it. Once the appropriate argument is called the promise state changes. +```javascript +const getData = url => new Promise( (resolve, reject) => { + request(url, (err, res, body) => { + if (err) reject(new Error('invalid API call')) + resolve(body) + }) +}) +``` +This example creates a `Promise` that wraps a standard callback used to handle an API call. Notice that there are two possible cases handled here. + +1. If the API call throws an error we set the promise state to _rejected_. +2. If the API call succeeds we set the promise state to _fulfilled_. + +As you can see it it simple to wrap any async callbacks in promises but how are these called? + +### 6.2 Consuming a Promise + +To use promises we need a mechanism that gets triggered as soon as a promise changes state. A promise includes a `then()` method which gets called if the state changes to _fulfilled_ and a `catch()` method that gets called if the state changes to _rejected_. +```javascript +const aPromise = getData('http://api.fixer.io/latest?base=GBP') + +aPromise.then( data => console.log(data)) + +aPromise.catch( err => console.error(`error: ${err.message}`) ) +``` +In this example we create a _new Promise_ and store it in a variable. It get executed _immediately_. The second line calls its `then()` method which will get executed if the promise state becomes _fulfilled_ (the API call is successful). The parameter will be assigned the value passed when the `resolve()` function is called in the promise, in this case it will contain the JSON data returned by the API call. + +If the state of the promise changes to _rejected_, the `catch()` method is called. The parameter will be set to the value passed to the `reject()` function inside the promise. In this example it will contain an `Error` object. + +This code can be written in a more concise way by _chaining_ the promise methods. +```javascript +getData('http://api.fixer.io/latest?base=GBP') + .then( data => console.log(data)) + .catch( err => console.error(`error: ${err.message}`)) +``` +Because the Promise is executed immediately we don't need to store it in a variable. The `.then()` and `.catch()` methods are simply chained onto the promise. This form is much more compact and allows us to chain multiple promises together to solve more complex tasks. + +### 6.3 Chaining Promises + +The real power of promises comes from their ability to be _chained_. This allows the results from a promise to be passed to another promise. All you need to do is pass another promise to the `next()` method. +```javascript +const getData = url => new Promise( (resolve, reject) => { + request(url, (err, res, body) => { + if (err) reject(new Error('invalid API call')) + resolve(body) + }) +}) + +const printObject = data => new Promise( resolve => { + const indent = 2 + data = JSON.parse(data) + const str = JSON.stringify(data, null, indent) + console.log(str) + resolve() +}) + +getData('http://api.fixer.io/latest?base=GBP') + .then( data => printObject(data)) + .catch(err => console.error(`error: ${err.message}`)) +``` +Notice that we pass the `printObject` promise to the `then()` method. The data passed back from the `getData` promise is passed to the `printObject` promise. + +If a promise only takes a single parameter and this matches the data passed back when the previous promise _fulfills_ there is a more concise way to write this. + +```javascript +getData('http://api.fixer.io/latest?base=GBP') + .then(printObject) + .catch(err => console.error(`error: ${err.message}`)) +``` + +### 6.4 Test Your Knowledge + +Run the `promises.js` script, its functionality should be familiar to the `currency.js` script you worked with in chapter 3. + +Open the `promises.js` script and study the code carefully. Notice that it defines 5 promises and chains them together. You are going to extend the functionality by defining some additional promises and adding them to the promise chain. 1. modify the script to ask for the currency to convert to and display only the one conversion rate. 2. instead of printing the exchange rate, ask for the amount to be converted and them return the equivalent in the chosen currency diff --git a/05 Version Control.md b/05 Version Control.md index d4c967d..440ce81 100644 --- a/05 Version Control.md +++ b/05 Version Control.md @@ -1,19 +1,66 @@ # Version Control -1. Git Remotes * -2. Branching -3. GitFlow +- Where is my code? +- My files are corrupted +- What has changed and when? +- I’ve broken my program and can’t fix it +- I need to work on a different computer +- My team members are all working on the same file! +- Who has modified the files and when? +- Who has been doing the programming? -## 1 Git Remotes +Revision control +- The management of changes to documents +- Each changes are usually identified by a revision number +- Each revision has a timestamp and the person responsible +- Revisions can be compared, restored, and merged + +What is Git? + +- Git is a version control system (VCS) +- It can help you keep track of files that are frequently changed +- It supports distributed development +- Its Open Source (you can download and install it for free) +- Alternatives: Mercurial, subverson (SVN) + +In this chapter we will be covering the use of Git to version control our source code. + +1. Working with Git Locally * +2. Git Remotes * +3. Branching +4. GitFlow + +## 1 Working with Git Locally + +Even if you are not working as part of a team, Git can offer a number of advantages. In this section you will learn how to use Git to manage your code within your local development environment. + +### 1.1 Configuration + +Before carrying out any work, the repository needs to be configured. This involves TODO + +### 1.1 Test Your Knowledge + +Create a new directory on your computer and, after navigating into it initialise an empty repository. +```shell +$ mkdir local_git/ +$ cd local_git/ +$ ls -a + . .. + +$ git init + Initialised empty Git repository in /home/johndoe/Documents/local_git/.git/ + +$ ls -a + . .. .git ``` -git clone https://github.coventry.ac.uk/304CEM-1718SEPJAN/currency.git -``` +Running the `git init` command _initializes_ the repository and creates a new hidden directory called `.git/`. This contains all the information required to track your code changes. +next we need to add our user details and the preferred editor to the local configuration file which is kept in the `.git/` directory. Substitute your own name and email address. Since the **nano** text editor is far easier to use than the default **Vim** editor we will specify this as our default one. Finally we tell Git to cache our username and password for an hour (3600 seconds). ``` $ git config user.name "John Doe" -$ git config user.email johndoe@example.com +$ git config user.email 'johndoe@example.com' $ git config core.editor 'nano' $ git config credential.helper cache $ git config credential.helper 'cache --timeout=3600' @@ -24,25 +71,177 @@ $ git config --list user.email=johndoe@example.com ``` -### 1.1 Commits +Now we will create a new document in the `local_git/` directory. +``` +$ touch index.js +$ ls -a + . .. .git index.js +``` +Git should have tracked the changes in the project directory and noticed that there is an additional file. +``` +$ git status + On branch master + + Initial commit + Untracked files: + (use "git add ..." to include in what will be committed) + + index.js + + nothing added to commit but untracked files present (use "git add" to track) +``` +As you can see, the new `index.js` file is not currently being tracked. Let's enable tracking for this file. This is done in two steps, files are staged and then the staged files are committed to the repository with a commit message that explains the changes. +``` +$ git status + On branch master + + Initial commit + + Changes to be committed: + (use "git rm --cached ..." to unstage) + + new file: index.js + +$ git commit +``` +This will open the **Nano** text editor (the one we specified as our default) so we can add a commit message. +``` + +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# On branch master +# +# Initial commit +# +# Changes to be committed: +# new file: index.js +# + + + [ Read 10 lines ] +^G Get Help ^O Write Out ^W Where Is ^K Cut Text ^J Justify ^C Cur Pos ^Y Prev Page +^X Exit ^R Read File ^\ Replace ^U Uncut Text ^T To Spell ^_ Go To Line ^V Next Page +``` +Enter the text `added index.js file` on the top line then save using _ctrl+o_ and finally quit using _ctrl+x_ (all available commands are listed along the bottom of the editor window). You will see the following message in the terminal window. +``` +[master (root-commit) d9036c2] added index.js file + 1 file changed, 0 insertions(+), 0 deletions(-) + create mode 100644 index.js +``` +To see the most recent commits you can use the `git log` command. ``` $ git log -commit 51f469eb41eb486c4316a97e7badc0ec9af36cb5 -Author: Mark Tyers -Date: Mon Jun 12 10:24:18 2017 +0100 +commit d9036c2bdf224ea72981eaa095ef76931c92e31d +Author: John Doe +Date: Fri Jun 16 09:04:00 2017 +0100 - renamed files + added index.js file -commit d3ef104463d3bb33b8b8862fe986e8b93038ade3 -Author: Mark Tyers -Date: Mon Jun 12 07:45:22 2017 +0100 +``` +If we check the status of the repository we should see that there are no further files to commit. +``` +$ git status +On branch master +nothing to commit, working tree clean +``` + +Next we will edit the index.js file. You can either open it in a visual code editor or use `nano index.js`. Enter the following then save your changes. +```javascript +// this is a simple script to show how git works +console.log('Hello Git!') +``` +If we check our repository status. +``` +$ git status +On branch master +Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: index.js + +no changes added to commit (use "git add" and/or "git commit -a") +``` +This time we will use a shortcut that stages the changes and makes a commit all from a single `git commit` command. +``` +$ git commit -am 'added message to index.js' + [master 721df6d] added message to index.js + 1 file changed, 2 insertions(+) +``` +The `-a` flag automatically stages all modified files and the `-m` flag allows us to add the commit message without opening our text editor. +``` +$ git log +commit 721df6dc9368bbe948be86fc19e696b7059dce5f +Author: Mark Tyers +Date: Fri Jun 16 09:17:29 2017 +0100 + + added message to index.js + +commit d9036c2bdf224ea72981eaa095ef76931c92e31d +Author: Mark Tyers +Date: Fri Jun 16 09:04:00 2017 +0100 + + added index.js file +``` +As you can see, there are now two commits in our repository. If there are too many commits to fit on the screen you can navigate using `space` for the next page, `w` for the previous page and `q` to quit. + +## 2 Git Remotes + +In the previous section you learned how to use Git to track local changes. In this section you will learn how to use remote git services. + +You will be shown two ways to configure this depending on whether you already have a local Git repository. The examples will be using [GitHub](www.github.com) but these will work equally with other services such as [GitLab](www.gitlab.com) or [BitBucket](www.bitbucket.com). + +TODO + +``` +git clone https://github.coventry.ac.uk/304CEM-1718SEPJAN/currency.git +``` + +### 2.1 Adding a Remotes + +If you already have a local Git repository (such as the one in your `local_repo/` directory), you can connect this to a remote. + +#### 2.1.1 Test Your Knowledge + +Create an account on GitHub.com and log in. Click on the green **New repository** button and in the _Repository name_ field enter `remote-repo`. Leave the description blank and click on the green **Create repository** button. - added start of gitflow +near the top of the screen you will see a section called _Quick setup_ which will be displaying a url. There are two URLs, one uses HTTP and the other uses SSH/Git. Make sure the **HTTPS** option is selected and copy the url to the clipboard, it should look something like this. ``` -You navigate using `space` for the next page, `w` for the previous page and `q` to quit. +https://github.com/johndoe/remote-repo.git +``` +In the terminal, make sure you are still in the `local_git/` directory and add the GitHub remote to your project. +``` +$ git remote +$ git remote add origin https://github.com/johndoe/remote-repo.git +$ git remote + origin +``` +The first time we view the remotes none are shown. We then add our GitHub remote and assign it the name `origin`, which is the standard name used by Git. If we now list the remotes we see that origin has now been added. + +Finally we push our commits to the remote repository on GitHub. +```$ git push origin --all + Username for 'https://github.com': johndoe + Password for 'https://johndoe@github.com': + Counting objects: 6, done. + Delta compression using up to 8 threads. + Compressing objects: 100% (3/3), done. + Writing objects: 100% (6/6), 506 bytes | 0 bytes/s, done. + Total 6 (delta 0), reused 0 (delta 0) + To https://github.com/marktyers/remote-repo.git + * [new branch] master -> master + ``` + If we refresh the repository web page on GitHub you should see the `index.js` file. The complete repository has been pushed including both our commits which can be seen under the _commits_ tab. -### 1.2 Remotes + If you select the _commits_ tab you should see your profile picture and name next to each of the two commits. + +![GitHub commits](.images/github_commits.png) + + If this has not happened it means that the name and email you have stored in the local git config settings _don't match the details you have stored on GitHub_. You can't retrospectively fix the current commits but, if you update the local settings, all future commits will show your details correctly. + +### 2.2 Cloning a Repository + +TODO ``` $ git remote show diff --git a/exercises/03_async/promises.js b/exercises/03_async/promises.js index 368fa40..39696d4 100644 --- a/exercises/03_async/promises.js +++ b/exercises/03_async/promises.js @@ -15,19 +15,19 @@ const checkValidCurrencyCode = code => new Promise( (resolve, reject) => { request('http://api.fixer.io/latest', (err, res, body) => { if (err) reject(new Error('invalid API call')) const rates = JSON.parse(body).rates - if (!rates.hasOwnProperty(code)) it.throw(new Error(`invalid currency code ${code}`)) - resolve() + if (!rates.hasOwnProperty(code)) reject(new Error(`invalid currency code ${code}`)) + resolve(code) }) }) -const getData = url => new Promise( (resolve, reject) => { - request(url, (err, res, body) => { +const getData = code => new Promise( (resolve, reject) => { + request(`http://api.fixer.io/latest?base=${code}`, (err, res, body) => { if (err) reject(new Error('invalid API call')) resolve(body) }) }) -const printObject = data => new Promise( (resolve) => { +const printObject = data => new Promise( resolve => { const indent = 2 data = JSON.parse(data) const str = JSON.stringify(data, null, indent) @@ -35,14 +35,13 @@ const printObject = data => new Promise( (resolve) => { resolve() }) +const exit = () => new Promise( () => { + process.exit() +}) + getInput('enter base currency') - .then( data => { - this.base = data - }) - .then( () => checkValidCurrencyCode(this.base)) - .then( () => getData(`http://api.fixer.io/latest?base=${this.base}`)) - .then( data => printObject(data)) - .then( () => { - process.exit() - }) + .then(checkValidCurrencyCode) + .then(getData) + .then(printObject) + .then(exit) .catch( err => console.error(`error: ${err.message}`))