Open this page
There are many excellent tutorials on the internet discussing Functional Programming. Thus, it is perhaps counter counterproductive to follow the traditional path discussing this topic. Instead, we will try to focus on aspects of Functional Programming as it is used by modern web applications developer.
These snippets were created specifically for the presentation to the programming club at IliaUni.
These snippets do not require any framework, complication, or any dependencies not included.
To demonstrate how Functional Style is used with Reactive Programming, I initially decided to mock some of the basic behaviours of Microsoft's Reactive Extensions library. These mocks are still available in this repo and could be used for demonstration. However, I later decided to include the actual Reactive Extensions from Microsoft, in case we need more functionality during the presentation. Microsoft's library should be automatically loaded in the brower, once the included html file is opened.
We will briefly look at some of the basic ideas in Functional Programming.
We may use simple snippets in the file 1-functional.js
Then we will try to see Functional Programming in action. Perhaps with Promises and Observables.
The snippets were written to be executable within the browser console.
Open the index.html file in the browser and open the console.
Some of the most basic snippets are available in file 1-functional.js
, which can be copy/pasted into the browser console.
- Reactive Extensions for JavaScript (
RxJs
) from Microsoft should automatically load - Function
curry(f)
converts regular functions to curried functions - Function
show(message: string, clear = true)
puts messages on the pageshow()
is a curried function- Usage:
show('Hello')
orshow('Hello', false)
- You can test if your code on the page is blocking or non-blocking. Do so by clicking the button
- Function
primesAsync()
will asynchronously load prime numbers from an API (via CORS proxy). Returns a Promise- Sample usage:
primesAsync().then(console.log)
- Sample usage:
- Function
primes$()
will return a stream of primes- Sample usage:
primes$().subscribe(console.log, console.warn, console.log.bind(console, '%cDone', 'color:red'));
- Sample usage:
For these examples, turn on the Non-Blocking Test
by clicking the button on the page.
This is trivial, so we may try to quickly set up a routine to do it and observe if the resulting code will be blocking or non-blocking.
primes$().subscribe(
console.log,
console.warn,
console.log.bind(console, '%cDone', 'color:red')
)
// Get primes on the page - (Turn on non-blocking test to confirm that script is non-blocking)
concat(
of(null).pipe(tap(show('Getting primes')), ignoreElements()),
primes$(1e5 /* start from */, 0 /* delay */).pipe(takeUntil(stop$)),
of('No More Primes ;)')
).subscribe(show(_, false) /* curried function */, console.warn, console.log.bind(console, 'Done'))