SlideShare a Scribd company logo
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/

More Related Content

What's hot

C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
corehard_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 2014
Fantix King 王川
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
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
NativeBoost
ESUG
 
The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE
Andrey Karpov
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
Doug Hawkins
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-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
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
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
Yung-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 right
Platonov 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 Programmers
Appier
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien 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
 

What's hot (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 ...
 

Similar to Node.js System: The Landing

How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
Rainer Schuettengruber
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
Rodolfo Carvalho
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
Giorgio Zoppi
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy 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 2016
Manoj Kumar
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
Fred Chien
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov 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 practices
Ankit Rastogi
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
rsebbe
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
Fujio Kojima
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
Simen Li
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
Troy Miles
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
Celery
CeleryCelery

Similar to 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
 

More from Haci Murat Yaman

MQTT meets AMQP
MQTT meets AMQPMQTT meets AMQP
MQTT meets AMQP
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 Implementation
Haci 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 GraphQL
Haci Murat Yaman
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Haci 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 1
Haci 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 land
Haci Murat Yaman
 

More from 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
 

Recently uploaded

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 

Recently uploaded (20)

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 

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/