Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

10 custom events #45

Open
wants to merge 33 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
533ca28
initial code added (index.html)
Apr 18, 2017
b1c3817
closure exercise description added
Apr 18, 2017
c6c8d4b
closure exercise solved
Apr 18, 2017
6d43c82
closure exercise solved
Apr 18, 2017
38df364
module pattern exercise added
Apr 18, 2017
948e44f
module pattern exercise solved
Apr 18, 2017
38391e6
instructions for constructor function exercise
Apr 18, 2017
4f620a7
construction function exercise solved
Apr 18, 2017
b38bc1f
es6 syntax exercise added
Apr 18, 2017
10c7b34
es6 syntax exercise solved
Apr 18, 2017
dd94c79
unnecessary lines deleted
Apr 18, 2017
303df0d
promise exercise description added
Apr 18, 2017
183c32c
promise exercise solved
Apr 18, 2017
e5a8e7f
managing dependencies description added
Apr 19, 2017
e70c2a8
managing-deps exercise solved
Apr 19, 2017
bf39b1a
package.json and karma config added
Apr 20, 2017
3c73149
karma config updated (use chrome)
Apr 20, 2017
f5660c3
karma config updated (clear test files)
Apr 20, 2017
5689294
exercise 7 solution added
Apr 20, 2017
5cb40ee
testing on node exercise solved
Apr 20, 2017
67a437b
js in the browser exercise solved
Apr 22, 2017
840ca1c
custom event exercise solved / progress bar shown
Apr 22, 2017
0480bc7
readme updated
Apr 23, 2017
3acc000
gitignore / readme
Apr 23, 2017
04f6116
readme.md updated
Apr 24, 2017
de7a684
browser tests refactored
Apr 27, 2017
2c1dc6a
repo update
tszewcow Feb 19, 2018
84eea04
html code adjusted for bootstrap 4
tszewcow Feb 20, 2018
069dc1f
Merge pull request #16 from tszewcow/10-custom-events
tszewcow Feb 23, 2018
345683f
hoek npm package version updated due to security vulnerability / phan…
Apr 27, 2018
001d392
Merge pull request #29 from tszewcow/10-custom-events
tszewcow Apr 27, 2018
54798f8
add Apache Licence, code of conduct, contributing guide and templates
Jorge-Dacal Jul 25, 2018
38c8fcd
Merge branch 'master' into 10-custom-events
kdrzazga Jun 4, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions atm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const person = new Person('John', 'Example', [new Account(1500, 'EUR', 1), new Account(-2500, 'EUR', 2)]);

const atm = (() => {
// add person name
document.querySelector('.card-title').innerHTML = `${person.firstName} ${person.lastName}`;

// list person accounts
const card = document.querySelector('.card-body');

for (let account of person.accounts) {
const paragraph = document.createElement('p');
const paragraphText = document.createTextNode(`Account Number: ${account.number}, Balance: `);

paragraph.appendChild(paragraphText);

const span = document.createElement('span');
span.id = 'account' + account.number;
span.innerText = account.balance;

paragraph.appendChild(span);

card.appendChild(paragraph);
}

// progress bar handling
const container = document.querySelector('.container');
const progress = document.querySelector('.progress');
const button = document.querySelector('button');
container.addEventListener('myEvent', (e) => {
progress.hidden = !e.detail.showProgress;
});

return {
withdrawMoney: function () {
const number = +document.querySelector('#number').value;
const amount = +document.querySelector('#amount').value;

const event = new CustomEvent('myEvent', {
detail: { showProgress: true },
bubbles: true
});

button.disabled = true;
button.dispatchEvent(event);

if (number && amount) {
event.detail.showProgress = false;

person.withdraw(number, amount).then(() => {
document.querySelector(`span#account${number}`).innerHTML = +document.querySelector(`span#account${number}`).innerHTML - amount;

button.dispatchEvent(event);
button.disabled = false;

}).catch((reason) => {
console.warn(reason);
button.dispatchEvent(event);
button.disabled = false;
});
}
},
onInputChange: function () {
const number = +document.querySelector('#number').value;
const amount = +document.querySelector('#amount').value;

if (number > 0 && amount > 0) {
button.disabled = false;
} else {
button.disabled = true;
}
}
}
})();
59 changes: 59 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS Training code</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<style>
.card {
border: 1px solid lightgray;
padding: 5px;
margin-bottom: 20px;
}
</style>
</head>

<body>
<div class="container">
<h1>JS Training</h1>

<div class="progress" hidden>
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="100" aria-valuemin="0"
aria-valuemax="100" style="width: 100%"></div>
</div>

<div class="card">
<div class="card-body">
<h4 class="card-title"></h4>
<p class="card-text">Accounts:</p>
</div>
</div>

<div class="form-inline">
<label class="sr-only" for="number">Number</label>
<input onkeyup="atm.onInputChange()" onchange="atm.onInputChange()" type="number" min="0" class="form-control mb-2 mr-sm-2 mb-sm-0"
id="number" placeholder="Account number...">

<label class="sr-only" for="amount">Amount</label>
<input onkeyup="atm.onInputChange()" onchange="atm.onInputChange()" type="number" min="0" step="10" class="form-control mb-2 mr-sm-2 mb-sm-0"
id="amount" placeholder="Amount...">

<button onclick="atm.withdrawMoney()" class="btn btn-primary" disabled>Submit</button>
</div>

</div>

<script src="main.js"></script>
<script src="atm.js"></script>
</body>

</html>
69 changes: 69 additions & 0 deletions main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
console.log('hello from main js');

class Account {
constructor(balance, currency, number) {
this.balance = balance;
this.currency = currency;
this.number = number;
};
};

class Person {
constructor(firstName, lastName, accounts) {
this.firstName = firstName;
this.lastName = lastName;
this.accounts = accounts;
};

addAccount(account) {
this.accounts.push(account);
};

sayHello() {
return `Hi, my name is ${this.firstName} ${this.lastName} and I have ${this.accounts.length} bank account(s) with total balance ${this._calculateBalance()}`;
};

filterPositiveAccounts() {
return this.accounts.filter(account => account.balance > 0);
};

findAccount(accountNumber) {
return this.accounts.find(account => account.number === accountNumber);
};

withdraw(accountNumber, amount) {
const promise = new Promise((resolve, reject) => {
const foundAccount = this.findAccount(accountNumber);

if (foundAccount && foundAccount.balance >= amount) {
setTimeout(() => {
foundAccount.balance = foundAccount.balance - amount;
resolve(`Operation successful, withdrawn ${amount} from account ${accountNumber}, remaining balance ${foundAccount.balance}`);
}, 3000);
} else if (!foundAccount) {
reject('Incorrect account number')
} else {
reject(`Not enough funds on account number ${accountNumber}`);
}
});

return promise;
};

_calculateBalance() {
let totalBalance = 0;

for (let account of this.accounts) {
totalBalance = totalBalance + account.balance;
}

return totalBalance;
};
};

if (typeof module !== 'undefined') {
module.exports = {
Person: Person,
Account: Account
}
}
94 changes: 94 additions & 0 deletions main.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
describe('Person class tests', () => {

const firstName = 'John';
const lastName = 'Example';
let person;

beforeEach(() => {
person = new Person(firstName, lastName, [new Account(1500, 'EUR', 1234)]);
});

it('should initialize new person object', () => {
// given when then
expect(person.firstName).toBe(firstName);
expect(person.lastName).toBe(lastName);
expect(person.accounts.length).toBe(1);
expect(person.accounts[0].balance).toBe(1500);
expect(person.accounts[0].currency).toBe('EUR');
expect(person.accounts[0].number).toBe(1234);
});

it('should add account', () => {
// given
const account = new Account(200, 'EUR', 9999);

// when
person.addAccount(account);

// then
expect(person.accounts.length).toBe(2);
expect(person.accounts[1]).toEqual(account);
});

it('should introduce itself', () => {
// given when then
expect(person.sayHello()).toBe('Hi, my name is John Example and I have 1 bank account(s) with total balance 1500');
});

it('should filter accounts with positive balance', () => {
// given
const account = new Account(-100, 'PLN', 1010);

// when
person.addAccount(account);
const positiveAccounts = person.filterPositiveAccounts();

// then
expect(positiveAccounts.length = 1);
expect(positiveAccounts[0].balance).toBeGreaterThanOrEqual(0);
});

it('should find account by its number', () => {
// given
const accountNumber = 1234;

// when
const foundAccount = person.findAccount(accountNumber);

// then
expect(foundAccount.number).toBe(accountNumber);
});

it('should withdraw money', (done) => {
// given when
const promise = person.withdraw(1234, 200);

// then
promise.then(() => {
expect(person.accounts[0].balance).toBe(1300);
done();
});
});

it('should not withdraw money when account not found', (done) => {
// given when
const promise = person.withdraw(5, 2000);

// then
promise.catch((reason) => {
expect(reason).toBe('Incorrect account number');
done();
});
});

it('should not withdraw money when there is not enough money on the account', (done) => {
// given when
const promise = person.withdraw(1234, 20000);

// then
promise.catch((reason) => {
expect(reason).toBe('Not enough funds on account number 1234');
done();
});
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@
"dependencies": {
"bootstrap": "^4.0.0"
}
}
}
28 changes: 28 additions & 0 deletions tests/main-node.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const chai = require('chai');
const expect = chai.expect; // we are using the "expect" style of Chai
const Person = require('../main.js').Person;
const Account = require('../main.js').Account;


describe('Person class tests', () => {

let person;
const firstName = 'John';
const lastName = 'Example';
const accounts = [new Account(1500, 'EUR', 1234)];


beforeEach(() => {
person = new Person(firstName, lastName, accounts);
});

it('should initialize new person object', () => {
// given when then
expect(person.firstName).to.equal(firstName);
expect(person.lastName).to.equal(lastName);
expect(person.accounts.length).to.equal(1);
expect(person.accounts[0].balance).to.equal(1500);
expect(person.accounts[0].currency).to.equal('EUR');
expect(person.accounts[0].number).to.equal(1234);
});
});