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

Recommended for you

Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD

SIMD machines — machines capable of evaluating the same instruction on several elements of data in parallel — are nowadays commonplace and diverse, be it in supercomputers, desktop computers or even mobile ones. Numerous tools and libraries can make use of that technology to speed up their computations, yet it could be argued that there is no library that provides a satisfying minimalistic, high-level and platform-agnostic interface for the C++ developer.

c++
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 -...

What do threads, atomic variables, mutexes, and conditional variables have in common? They are the basic building blocks of any concurrent application in C++, which are even for the experienced C++ programmers a big challenge. This massively changed with C++17 and change even more with C++20/23. What did we get with C++17, what can we hope for with C++20/23? With C++17, most of the standard template library algorithms are available in sequential, parallel, and vectorised variants. With the upcoming standards, we can look forward to executors, transactional memory, significantly improved futures and coroutines. To make it short. These are just the highlights from the concurrent and parallel perspective. Thus there is the hope that in the future C++ abstractions such as executors, transactional memory, futures and coroutines are used and that threads, atomic variables, mutexes and condition variables are just implementation details.

c++corehardconference
NativeBoost
NativeBoostNativeBoost
NativeBoost

NativeBoost is a library that allows Pharo code to interface with native code written in C/C++. It provides functions for calling external functions, handling basic data types, and working with structures. The tutorial demonstrates how to use NativeBoost to interface with the Chipmunk physics library from within Pharo. It shows defining types for structures like vectors, calling functions, and dealing with indirect function calls through pointers. Understanding native libraries, data types, and structures is necessary to interface Pharo with external C code using NativeBoost.

 
by ESUG
esug2013esugsmalltalk
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

Recommended for you

The Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDEThe Unicorn Getting Interested in KDE
The Unicorn Getting Interested in KDE

The document analyzes potential issues found by PVS-Studio in various KDE projects and libraries. It identifies several types of issues, including expressions that are always true or false, unsafe pointer usage before validation, missing keywords that could alter program logic, and unsafe realloc() usage. A total of 27 specific code fragments are highlighted across the different libraries and applications as demonstrating these kinds of issues.

pvs-studiokdestatic code analysis
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java

Overview of low-level concurrency guarantees of the Java Memory Model -- with some surprising examples of legal optimizations and their consequences.

concurrencyjvmjava
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted

Twisted is an event-driven networking engine written in Python. It provides tools for developing asynchronous network applications and services. Some key features of Twisted include an asynchronous reactor framework, support for deferreds/promises, common network protocols and services implemented, and application framework for building services.

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();

Recommended for you

Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics

The JVM JIT compiler and deoptimizer are triggered under certain conditions like method invocation counts, changes in program behavior, and hot spots. The JIT initially compiles code to generate fast machine instructions while the deoptimizer reverts back to interpreted execution if needed.

javajava virtual machinejava garbage collection
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013

Dynamic C++ presentation at ACCU 2013 Conference. http://accu.org/index.php/conferences/accu_conference_2013/accu2013_sessions#dynamic_c

poco c++ boost accu
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

The document discusses different approaches to implementing GPU-like programming on CPUs using C++AMP. It covers using setjmp/longjmp to implement coroutines for "fake threading", using ucontext for coroutine context switching, and how to pass lambda functions and non-integer arguments to makecontext. Implementing barriers on CPUs requires synchronizing threads with an atomic counter instead of GPU shared memory. Overall, the document shows it is possible to run GPU-like programming models on CPUs by simulating the GPU programming model using language features for coroutines and threading.

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
Обзор фреймворка Twisted
Maxim 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++AMP
Miller 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 Up
David 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
 
Day 1
Day 1Day 1
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
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
AqeelAbbas94
 
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

React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
SSTech System
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
avufu
 
Development of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML TechnologiesDevelopment of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML Technologies
MaisnamLuwangPibarel
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
confluent
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Asher Sterkin
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
Ortus Solutions, Corp
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
TwisterTools
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
sheqnetworkmarketing
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
Cultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational TransformationCultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational Transformation
Mindfire Solution
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdfAWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
karim wahed
 
How we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hoursHow we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hours
Ortus Solutions, Corp
 
NYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdfNYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdf
AUGNYC
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Livetecs LLC
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
Roshan Dwivedi
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
Mitchell Marsh
 
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple StepsSeamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Estuary Flow
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
Ortus Solutions, Corp
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
Severalnines
 

Recently uploaded (20)

React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
 
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
一比一原版英国牛津大学毕业证(oxon毕业证书)如何办理
 
Development of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML TechnologiesDevelopment of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML Technologies
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
 
Intro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AIIntro to Amazon Web Services (AWS) and Gen AI
Intro to Amazon Web Services (AWS) and Gen AI
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
Cultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational TransformationCultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational Transformation
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdfAWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
 
How we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hoursHow we built TryBoxLang in under 48 hours
How we built TryBoxLang in under 48 hours
 
NYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdfNYC 26-Jun-2024 Combined Presentations.pdf
NYC 26-Jun-2024 Combined Presentations.pdf
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
 
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple StepsSeamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
Seamless PostgreSQL to Snowflake Data Transfer in 8 Simple Steps
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
 
WEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service ProvidersWEBINAR SLIDES: CCX for Cloud Service Providers
WEBINAR SLIDES: CCX for Cloud Service Providers
 

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/