SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Node.js System:
The Landing Haci M. Yaman
29/4/2021
Content
1. Prototype-based OOP
• Sample Code
2. Asynchronous Programming
• Sample Code (a)
• Sample Code (b)
3. Automated Tests
• Sample Code
4. Sample Code (TypeScript)
5. Sample Code (Generators Functions)
6. Sample Code (Generics)
7. The End
1. Prototype-based OOP
• It is like working with templates and copying those templates
• Object prototypes are dynamic; they can be changed at run-time
• Objects based on those prototypes are also dynamic
• Prototypes can copy behaviour of other prototypes (Inheritance)
• Multiple prototypes can implement same behaviour (Polymorphism)
1. Sample Code (a)
// 1.a. generic object
const person0 = { name: 'Adam', age: 101, friends: [] };
person0.follow = friend => { this.friends.push(friend); };
const person1 = Object.create(person0);
// 1.b. we can also put it inside a 'factory' function and return person object
const makePerson = (name = '', age = 0, friends = []) => { /* create person0 */ return person0; };
// 2. function definition
function Person(name = '', age = 0, friends = []) {
this.name = name;
this.age = age;
this.friends = friends;
this.follow = friend => { this.friends.push(friend); };
}
const person2 = new Person('Becky', 102);
// 3. class definition
class PersonModel {
constructor(name = '', age = 0, friends = []) {
this.name = name;
this.age = age;
this.friends = friends;
}
follow(friend) { this.friends.push(friend); }
}
PersonModel.prototype.talk = sentence => { console.log(sentence); /* TODO use TTS engine */ }
const person3 = new PersonModel('Conor', 103);
Ref: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
2. Asynchronous Programming
• Callback functions: Fire and forget; we will call you back!
• Functions as arguments to other functions
• Timers: setTimeout(), setInterval()
• Promises: special object that “mimic” threads
• Special methods: then(), catch()
• Callback hell:
• Async/Await heaven
2. Sample Code (a)
// Timers
function showTime() { console.log(new Date()); }
const id = setInterval(showTime, 1000); // run every second
function stopShowingTime() { clearInterval(id); console.log('stopped'); process.exit(0); }
setTimeout(stopShowingTime, 10 * 1000); // run after ten seconds once
console.log('started');
// Promises
function promiseHandler(resolve, reject) {
const r = Math.random();
0.9 <= r // ternary expression used as statement
? resolve({ success: 'we got: ' + r }) // captured by then() callback
: reject({ error: 'sorry, we got: ' + r }); // captured by catch() callback
}
const randomPromise = new Promise(promiseHandler);
const startRandomPromise = () => {
randomPromise.then(console.info).catch(console.error);
}
startRandomPromise();
2. Sample Code (b)
// Async/Await
const puppeteer = require('puppeteer’);
const sleep = async (ms = 1000) => new Promise(resolve => setTimeout(resolve, ms));
async function countTheStars() {
let i = 0, limit = 10, duration = 60 * 1000, url = 'https://github.com/nodejs/node’;
let linkSelector = 'a.social-count', linkElement, linkText;
const browser = await puppeteer.launch();
const page = await browser.newPage();
while(i < limit) { // count the stars every minute ;)
await page.goto(url);
linkElement = await page.$(linkSelector);
if (linkElement) {
linkText = await page.evaluate(el => el.textContent, linkElement);
console.info(new Date(), 'stars', linkText);
}
await sleep(duration);
i++;
}
await browser.close();
}
countTheStars();
3. Automated Tests
• “Mocha is a feature-rich JavaScript test framework running on
Node.js and in the browser”
• Define test suites/cases by using simple function calls and callback functions
• Use async/await within callback functions, if preferred,
• “Chai is a BDD / TDD assertion library for node and the browser”
• Verify the expectations using chainable interfaces: expect, should, assert
3. Sample Code
// Automated tests
// myMathLib.js ======================================================
function euclideanDistance(pt1, pt2) {
const xDiff = Math.pow(pt1.x - pt2.x, 2);
const yDiff = Math.pow(pt1.y - pt2.y, 2);
return Math.sqrt(xDiff + yDiff);
}
module.exports = { euclideanDistance };
// myMathLib.test.js =================================================
const { expect } = require('chai');
const { euclideanDistance } = require('./myMathLib');
describe('euclideanDistance', () => {
it('should return 2 when points are [2,0] and [0,0]', () => {
const out = euclideanDistance({ x: 2, y: 0 }, { x: 0, y: 0 });
expect(out).to.equal(2);
});
});
// package.json ======================================================
// scripts: { "test": "mocha *.test.js" }
// command line: npm run test
4. Sample Code (TypeScript)
// TypeScript
// npm i typescript ts-node @types/node
// npm i -g typescript ts-node
// to generate tsconfig.json: tsc --init
// myMathLib.ts ====================================================
export interface Point {
x: number;
y: number;
}
export function euclideanDistance(pt1: Point, pt2: Point): number {
const xDiff: number = Math.pow(pt1.x - pt2.x, 2);
const yDiff: number = Math.pow(pt1.y - pt2.y, 2);
return Math.sqrt(xDiff + yDiff);
}
export default euclideanDistance;
// sample.ts ========================================================
import euclideanDistance, { Point } from './myMathLib';
const pt1a: Point = { x: 2, y: 0 }, pt1b: Point = { x: 0, y: 0 };
const pt2a: Point = { x: 2, y: 2 }, pt2b: Point = { x: -1, y: -1 };
const dist1: number = euclideanDistance(pt1a, pt1b);
const dist2: number = euclideanDistance(pt2a, pt2b);
console.log('the distance between', pt1a, 'and', pt1b, 'is', dist1);
console.log('the distance between', pt2a, 'and', pt2b, 'is', dist2);
//------------------------------
// console: ts-node ./sample.ts
5. Sample Code (Generator Functions)
// Generator Functions
function* fibonacciIterator(limit: number = Infinity) {
let old: number[] = [0, 1];
for (let i = 0; i < limit; i++) {
if (i === 0) yield old[0];
if (i === 1) yield old[1];
old[2] = old[1] + old[0];
yield old[2];
old[0] = old[1];
old[1] = old[2];
}
return -1; // special flag, we are done
}
// tsconfig.json compilerOptions.downlevelIteration = true
for (const n of fibonacciIterator(10)) {
console.log(n)
}
6. Sample Code (Generics)
import EventEmitter from 'events';
import { rword } from 'rword';
interface IRacer { name: string; age: number; dist: number; }
class Race<T extends IRacer = IRacer> extends EventEmitter {
private timer?: NodeJS.Timeout;
constructor(private racers: T[] = [], private distance = 1000) { super(); }
run() {
this.racers.forEach(h => { h.dist += 1 + Math.round(Math.random() * 10); });
this.racers = this.racers.sort((a, b) => b.dist - a.dist); // order: DESC
console.log(this.racers.map(h => `${h.name} at ${h.dist}`).join(' | ')); // TODO animate
if (this.distance <= this.racers[0].dist) this.stop(); // we have a winner
}
start() { this.timer = setInterval(() => this.run(), 1000); this.emit('start'); }
stop() { if (this.timer) clearInterval(this.timer); this.emit('stop', this.racers[0]); }
}
interface Horse extends IRacer {}
const makeHorse = (): Horse => ({
name: String(rword.generate(1)), age: 2 + Math.round(Math.random() * 10), dist: 0,
});
const horses: Horse[] = Array.from({ length: 5 }).map(makeHorse);
const race = new Race<Horse>(horses);
race.on('start', () => console.log('START'));
race.on('stop', winner => console.log('FINISH: the winner is', winner));
race.start();
The End
Thank you
Useful links:
https://nodejs.dev/learn
https://pptr.dev/
https://mochajs.org/
https://www.chaijs.com/
https://istanbul.js.org/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator
https://www.typescriptlang.org/

Weitere ähnliche Inhalte

Was ist angesagt?

C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxyginecorehard_by
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEAndrey Karpov
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013aleks-f
 
GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPMiller Lee
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersAppier
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 

Was ist angesagt? (20)

C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
Groovy
GroovyGroovy
Groovy
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 

Ähnlich wie Node.js System: The Landing

Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 

Ähnlich wie Node.js System: The Landing (20)

How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Day 1
Day 1Day 1
Day 1
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Celery
CeleryCelery
Celery
 

Mehr von Haci Murat Yaman

The API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationThe API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationHaci Murat Yaman
 
The API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLThe API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLHaci Murat Yaman
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1Haci Murat Yaman
 
The Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landThe Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landHaci Murat Yaman
 

Mehr von Haci Murat Yaman (6)

MQTT meets AMQP
MQTT meets AMQPMQTT meets AMQP
MQTT meets AMQP
 
The API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationThe API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and Implementation
 
The API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLThe API Journey: from REST to GraphQL
The API Journey: from REST to GraphQL
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1
 
The Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landThe Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno land
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 

Kürzlich hochgeladen (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 

Node.js System: The Landing

  • 1. Node.js System: The Landing Haci M. Yaman 29/4/2021
  • 2. Content 1. Prototype-based OOP • Sample Code 2. Asynchronous Programming • Sample Code (a) • Sample Code (b) 3. Automated Tests • Sample Code 4. Sample Code (TypeScript) 5. Sample Code (Generators Functions) 6. Sample Code (Generics) 7. The End
  • 3. 1. Prototype-based OOP • It is like working with templates and copying those templates • Object prototypes are dynamic; they can be changed at run-time • Objects based on those prototypes are also dynamic • Prototypes can copy behaviour of other prototypes (Inheritance) • Multiple prototypes can implement same behaviour (Polymorphism)
  • 4. 1. Sample Code (a) // 1.a. generic object const person0 = { name: 'Adam', age: 101, friends: [] }; person0.follow = friend => { this.friends.push(friend); }; const person1 = Object.create(person0); // 1.b. we can also put it inside a 'factory' function and return person object const makePerson = (name = '', age = 0, friends = []) => { /* create person0 */ return person0; }; // 2. function definition function Person(name = '', age = 0, friends = []) { this.name = name; this.age = age; this.friends = friends; this.follow = friend => { this.friends.push(friend); }; } const person2 = new Person('Becky', 102); // 3. class definition class PersonModel { constructor(name = '', age = 0, friends = []) { this.name = name; this.age = age; this.friends = friends; } follow(friend) { this.friends.push(friend); } } PersonModel.prototype.talk = sentence => { console.log(sentence); /* TODO use TTS engine */ } const person3 = new PersonModel('Conor', 103); Ref: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
  • 5. 2. Asynchronous Programming • Callback functions: Fire and forget; we will call you back! • Functions as arguments to other functions • Timers: setTimeout(), setInterval() • Promises: special object that “mimic” threads • Special methods: then(), catch() • Callback hell: • Async/Await heaven
  • 6. 2. Sample Code (a) // Timers function showTime() { console.log(new Date()); } const id = setInterval(showTime, 1000); // run every second function stopShowingTime() { clearInterval(id); console.log('stopped'); process.exit(0); } setTimeout(stopShowingTime, 10 * 1000); // run after ten seconds once console.log('started'); // Promises function promiseHandler(resolve, reject) { const r = Math.random(); 0.9 <= r // ternary expression used as statement ? resolve({ success: 'we got: ' + r }) // captured by then() callback : reject({ error: 'sorry, we got: ' + r }); // captured by catch() callback } const randomPromise = new Promise(promiseHandler); const startRandomPromise = () => { randomPromise.then(console.info).catch(console.error); } startRandomPromise();
  • 7. 2. Sample Code (b) // Async/Await const puppeteer = require('puppeteer’); const sleep = async (ms = 1000) => new Promise(resolve => setTimeout(resolve, ms)); async function countTheStars() { let i = 0, limit = 10, duration = 60 * 1000, url = 'https://github.com/nodejs/node’; let linkSelector = 'a.social-count', linkElement, linkText; const browser = await puppeteer.launch(); const page = await browser.newPage(); while(i < limit) { // count the stars every minute ;) await page.goto(url); linkElement = await page.$(linkSelector); if (linkElement) { linkText = await page.evaluate(el => el.textContent, linkElement); console.info(new Date(), 'stars', linkText); } await sleep(duration); i++; } await browser.close(); } countTheStars();
  • 8. 3. Automated Tests • “Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser” • Define test suites/cases by using simple function calls and callback functions • Use async/await within callback functions, if preferred, • “Chai is a BDD / TDD assertion library for node and the browser” • Verify the expectations using chainable interfaces: expect, should, assert
  • 9. 3. Sample Code // Automated tests // myMathLib.js ====================================================== function euclideanDistance(pt1, pt2) { const xDiff = Math.pow(pt1.x - pt2.x, 2); const yDiff = Math.pow(pt1.y - pt2.y, 2); return Math.sqrt(xDiff + yDiff); } module.exports = { euclideanDistance }; // myMathLib.test.js ================================================= const { expect } = require('chai'); const { euclideanDistance } = require('./myMathLib'); describe('euclideanDistance', () => { it('should return 2 when points are [2,0] and [0,0]', () => { const out = euclideanDistance({ x: 2, y: 0 }, { x: 0, y: 0 }); expect(out).to.equal(2); }); }); // package.json ====================================================== // scripts: { "test": "mocha *.test.js" } // command line: npm run test
  • 10. 4. Sample Code (TypeScript) // TypeScript // npm i typescript ts-node @types/node // npm i -g typescript ts-node // to generate tsconfig.json: tsc --init // myMathLib.ts ==================================================== export interface Point { x: number; y: number; } export function euclideanDistance(pt1: Point, pt2: Point): number { const xDiff: number = Math.pow(pt1.x - pt2.x, 2); const yDiff: number = Math.pow(pt1.y - pt2.y, 2); return Math.sqrt(xDiff + yDiff); } export default euclideanDistance; // sample.ts ======================================================== import euclideanDistance, { Point } from './myMathLib'; const pt1a: Point = { x: 2, y: 0 }, pt1b: Point = { x: 0, y: 0 }; const pt2a: Point = { x: 2, y: 2 }, pt2b: Point = { x: -1, y: -1 }; const dist1: number = euclideanDistance(pt1a, pt1b); const dist2: number = euclideanDistance(pt2a, pt2b); console.log('the distance between', pt1a, 'and', pt1b, 'is', dist1); console.log('the distance between', pt2a, 'and', pt2b, 'is', dist2); //------------------------------ // console: ts-node ./sample.ts
  • 11. 5. Sample Code (Generator Functions) // Generator Functions function* fibonacciIterator(limit: number = Infinity) { let old: number[] = [0, 1]; for (let i = 0; i < limit; i++) { if (i === 0) yield old[0]; if (i === 1) yield old[1]; old[2] = old[1] + old[0]; yield old[2]; old[0] = old[1]; old[1] = old[2]; } return -1; // special flag, we are done } // tsconfig.json compilerOptions.downlevelIteration = true for (const n of fibonacciIterator(10)) { console.log(n) }
  • 12. 6. Sample Code (Generics) import EventEmitter from 'events'; import { rword } from 'rword'; interface IRacer { name: string; age: number; dist: number; } class Race<T extends IRacer = IRacer> extends EventEmitter { private timer?: NodeJS.Timeout; constructor(private racers: T[] = [], private distance = 1000) { super(); } run() { this.racers.forEach(h => { h.dist += 1 + Math.round(Math.random() * 10); }); this.racers = this.racers.sort((a, b) => b.dist - a.dist); // order: DESC console.log(this.racers.map(h => `${h.name} at ${h.dist}`).join(' | ')); // TODO animate if (this.distance <= this.racers[0].dist) this.stop(); // we have a winner } start() { this.timer = setInterval(() => this.run(), 1000); this.emit('start'); } stop() { if (this.timer) clearInterval(this.timer); this.emit('stop', this.racers[0]); } } interface Horse extends IRacer {} const makeHorse = (): Horse => ({ name: String(rword.generate(1)), age: 2 + Math.round(Math.random() * 10), dist: 0, }); const horses: Horse[] = Array.from({ length: 5 }).map(makeHorse); const race = new Race<Horse>(horses); race.on('start', () => console.log('START')); race.on('stop', winner => console.log('FINISH: the winner is', winner)); race.start();
  • 13. The End Thank you Useful links: https://nodejs.dev/learn https://pptr.dev/ https://mochajs.org/ https://www.chaijs.com/ https://istanbul.js.org/ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator https://www.typescriptlang.org/