-
Notifications
You must be signed in to change notification settings - Fork 397
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fixed errors and added all solutions up to the end of 05_javascript
- Loading branch information
Showing
12 changed files
with
636 additions
and
170 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')}`) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
] |
Oops, something went wrong.