Skip to content

Commit

Permalink
fixed errors and added all solutions up to the end of 05_javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
bordasb committed Sep 29, 2020
1 parent e4321b0 commit 078678a
Show file tree
Hide file tree
Showing 12 changed files with 636 additions and 170 deletions.
363 changes: 205 additions & 158 deletions 05 JavaScript.md

Large diffs are not rendered by default.

21 changes: 13 additions & 8 deletions exercises/05_javascript/currency.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@

'use strict'

const request = require('request')
const fs = require('fs')

const symbol = 'GBP'
const symbol = 'EUR'

const printRates = (err, res, body) => {
if (err) throw 'could not complete request'
const data = JSON.parse(body) // this converts the formatted string into a javascript object
console.log(`for each EUR you will get ${data.rates[symbol]} ${symbol} today`)
const printRates = (err, data) => {
if (err) throw err
const parsedData = JSON.parse(data) // this converts the formatted string into a javascript object
for (const country of parsedData) {
if (country.code === symbol) {
console.log(`For each GBP you will get ${country.rate} ${symbol} today.`)
return
}
}
}

const url = 'currency.json'
const filePath = 'currency.json'

request.get( url, printRates)
fs.readFile(filePath, printRates)
8 changes: 7 additions & 1 deletion exercises/05_javascript/employee.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const employee = {
firstName: 'Colin',
'last name': 'Stephen',
startYear: 2010,
getName: () => `${this.firstName} ${this['last name']}`,
getName: function() {
return `${this.firstName} ${this["last name"]}`
},
setName: function(fullname) {
console.log(fullname)
const words = fullname.toString().split(' ')
Expand All @@ -23,3 +25,7 @@ console.log(jsonString)

employee.setName('Micky Mouse')
console.log(JSON.stringify(employee, null, 2))

// TypeError:
// const postCode = employee.address.postCode
// console.log(postCode)
7 changes: 4 additions & 3 deletions exercises/05_javascript/weather.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

const request = require('request')

const url = 'https://api.openweathermap.org/data/2.5/weather?q=coventry,uk&appid=44c39f3fa462f86b3fc88f5678e5c5ff'
const apiKey = '44c39f3fa462f86b3fc88f5678e5c5ff'
const cityName = 'coventry,uk'

request(url, (err, response, body) => {
request(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`, (err, response, body) => {
if(err) console.log(err.message)
console.log(`the body variable contains a ${typeof body}`)
const data = JSON.parse(body)
console.log(`the data variable contains an ${typeof data}`)
console.log(data)
})
})
81 changes: 81 additions & 0 deletions solutions/05_javascript/contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#!/usr/bin/env node

'use strict'

/* This script demonstrates how JavaScript can be used to handle exceptions. */

const readline = require('readline-sync')

/* any code that could throw an exception needs to be wrapped in a try block. If any line of code in the try block throws an exception the program immediately jumps to the catch block, passing the Error object thrown. Regardless of whether an error was thrown or not, the code in the finally block is run. */
try {
const email = String(readline.question('enter email address: '))
console.log('email is a '+typeof email+' and contains '+email)
validateEmail(email)
const score = Number(readline.question('assign score 1-10: '))
console.log('score is a '+typeof score+' and contains '+score)
validateScore(score)
const comment = String(readline.question('enter your comment : '))
validateComment(comment)
console.log(`Thank you ${email}. You gave us a rating of ${score}/10 with the comment "${comment}"`)
} catch(err) {
console.log(`${err.name} thrown`)
console.log(`The error message is: ${err.message}`)
console.log(err.stack)
} finally {
console.log('the script has finished')
}

/**
* Checks to see if the supplied parameter is formatted as a valid email
* address.
* @param {string} email - The email address to be checked.
* @returns {bool} the validity of the email address string
* @throws {TypeError} if the parameter is not a valid email address.
*/
function validateEmail(email) {
console.log(email)
const atIndex = email.lastIndexOf('@')
const dotIndex = email.lastIndexOf('.')
if ( email.length < 5
|| atIndex < 1
|| email.indexOf(' ') !== -1
|| email.indexOf('..') !== -1
|| dotIndex < atIndex
|| dotIndex === email.length - 1 ) {
throw TypeError
}
return true
}

/**
* Checks to see if the supplied parameter is a valid integer in the range 1-10.
* @param {string} score - The user-specified score.
* @returns {bool} whether the parameter is a valid integer in range
* @throws {TypeError} if the parameter is not a valid integer.
* @throws {RangeError} if the parameter is not in the range 1-10.
*/
function validateScore(score) {
const minScore = 0
const maxScore = 10
if (Number.isNaN(score) || score % 1 !== minScore) {
throw new TypeError('parameter is not a valid integer')
}
if (score < 1 || score > maxScore) {
throw new RangeError('parameter should be in the range 1-10')
}
return true
}

/**
* Checks to see if the supplied comment is 'valid'.
* @param {string} comment - The user-specified score.
* @returns {bool} whether the comment is 'valid'
* @throws {RangeError} if the comment is not long enough.
*/
function validateComment(comment) {
const minLen = 5
if (comment.length < minLen) {
throw new RangeError('comment should be at least 5 characters long')
}
return true
}
78 changes: 78 additions & 0 deletions solutions/05_javascript/employee.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#!/usr/bin/env node
/* eslint no-magic-numbers: 0 */

'use strict'

const employee = {
firstName: 'Colin',
'last name': 'Stephen',
startYear: 2010,
gender: 'male',
'date of birth': '1980-01-01',
getName: function() {
return `${this.firstName} ${this["last name"]}`
},
setName: function(fullname) {
console.log(fullname)
const words = fullname.toString().split(' ')
console.log(words)
console.log(this)
this.firstName = words[0] || ''
this['last name'] = words[1] || ''
},
get details() {
return `firstName: ${this.firstName}, lastName: ${this["last name"]}, startYear: ${this.startYear}, gender: ${this.gender}, DoB: ${this["date of birth"]}`
},
get yearsWorked() {
return (new Date().getFullYear() - this.startYear)
},
set name(fullname) {
const names = fullname.toString().split(' ')
this.firstName = names[0]
this["last name"] = names[1]
}
}

const jsonString = JSON.stringify(employee, null, 2)
console.log(jsonString)

employee.setName('Micky Mouse')
console.log(JSON.stringify(employee, null, 2))

// TypeError:
// const postCode = employee.address.postCode
// console.log(postCode)

const university = {
year1: {
a101: 'something11',
b104: 'something12',
c134: 'something13'
},
year2: {
d201: 'something21',
e204: 'something22',
f234: 'something23'
},
year3: {
g301: 'something31',
h304: 'something32',
i334: 'something33'
}
}

const study01 = university.year1
for(const code in study01) console.log(`${code} ${study01[code]}`)

const {year1: year1, year2: year2, year3: year3} = university

delete employee.startYear
employee.startYear = '2010'

String.prototype.toArray = function() {
return this.split('')
}
Array.prototype.toStr = function() {
return this.join('')
}
console.log('foobar'.toArray().toStr())
106 changes: 106 additions & 0 deletions solutions/05_javascript/maths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/env node
/* eslint no-magic-numbers: 0 */

'use strict'

function largestNumber(a, b) {
if (a > b) return a
if (b > a) return b
return null
}

const biggest = largestNumber(5, 8)
console.log(biggest)
// the code below achieves the same using the 'spread operator'
const nums = [5, 8]
const biggest2 = largestNumber(...nums)
console.log(biggest2)

// example using the arguments object
function add() {
let total = 0
console.log(arguments)
console.log(arguments['1'])
for(const arg of arguments) {
total += arg
}
return total
}

const addNums = add(1, 2, 3, 4)
console.log(addNums)


// example using a rest parameter
function add2(...values) {
let total = 0
console.log(values)
for (let i=0; i<values.length; i++) {
total += values[i]
}
return total
}

const addNums2 = add2(1, 2, 3, 4)
console.log(addNums2)


// example with default parameter
function divide(dividend, divisor=1) {
const quotient = dividend / divisor
return quotient
}

const quotient = divide(42, 2)
console.log(`calling the divide function with '2' paramters: ${quotient}`)

const quotient2 = divide(42)
console.log(`calling divide function with '1' parameter: ${quotient2}`)

// function expression using the `function` keyword
const remainder = function(dividend, divisor) {
const quotient = Math.floor(dividend / divisor)
return dividend - quotient * divisor
}

const rem = remainder(8, 5)
console.log(`remainder: ${rem}`)

// function expression using arrow syntax (preferred)
const remainder2 = (dividend, divisor) => dividend - Math.floor(dividend / divisor) * divisor
console.log('remainder2: ' + remainder2(13, 4))

// function expression using arrow syntax and one parameter
const sqr = num => num * num
console.log(sqr(4))

function multiply(a = 1, b = 1) {
return a * b
}
console.log(multiply(3, 5))

function divideThis(dividend, divisor = 1) {
return dividend / divisor
}
console.log(divideThis(5, 2))

function average(...numbers) {
if (numbers.length === 0) return 0
let sum = 0
for (const number of numbers) sum += number
return sum / numbers.length
}
console.log(`average of [2, 4, 6]: ${average(2, 4, 6)}`)

const squareRoot = a => Math.sqrt(a)
console.log(`squareRoot of 4096: ${squareRoot(4096)}`)

const longest = (...strings) => strings.length === 0 ? null : strings.reduce((longestString, currentString) => currentString.length > longestString.length ? currentString : longestString)
// simple version without using reduce:
// const longest = (...strings) => {
// if (strings.length === 0) return null
// let longest = strings[0]
// for (const string of strings) if (string > longest) longest = string
// return longest
// }
console.log(`longest of ['a', 'aaa', 'aa']: ${longest('a', 'aaa', 'aa')}`)
12 changes: 12 additions & 0 deletions solutions/05_javascript/quotes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env node

'use strict'

require('fs').readFile('quotes.json', (err, data) => {
if (err) console.log(err)
const quotesArray = JSON.parse(data)
console.log(quotesArray)
for (const quoteObject of quotesArray) {
console.log(quoteObject.quote)
}
})
42 changes: 42 additions & 0 deletions solutions/05_javascript/quotes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[
{
"quote":"We know what we are, but know not what we may be.",
"author":"William Shakespeare"
},
{
"quote":"Perfection is not attainable, but if we chase perfection we can catch excellence.",
"author":"Vince Lombardi"
},
{
"quote":"Do your little bit of good where you are; it's those little bits of good put together that overwhelm the world.",
"author":"Desmond Tutu"
},
{
"quote":"My mission in life is not merely to survive, but to thrive; and to do so with some passion, some compassion, some humor, and some style.",
"author":"Maya Angelou"
},
{
"quote":"We must let go of the life we have planned, so as to accept the one that is waiting for us.",
"author":"Joseph Campbell"
},
{
"quote":"The measure of who we are is what we do with what we have.",
"author":"Vince Lombardi"
},
{
"quote":"Don't judge each day by the harvest you reap but by the seeds that you plant.",
"author":"Robert Louis Stevenson"
},
{
"quote":"I hated every minute of training, but I said, 'Don't quit. Suffer now and live the rest of your life as a champion.'",
"author":"Muhammad Ali"
},
{
"quote":"Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.",
"author":"Buddha"
},
{
"quote":"How wonderful it is that nobody need wait a single moment before starting to improve the world.",
"author":"Anne Frank"
}
]
Loading

0 comments on commit 078678a

Please sign in to comment.