Skip to content

Instantly share code, notes, and snippets.

View XoseLluis's full-sized avatar

XoseLluis XoseLluis

  • Xixón, Asturies
View GitHub Profile
@XoseLluis
XoseLluis / Meal.js
Last active October 10, 2021 09:23
Use case for coroutines
export class Meal{
constructor(name, dishes, dessert, drinks){
this.name = name
this.dishes = dishes;
this.dessert = dessert;
this.drinks = drinks;
}
addMedicines(medicines){
this.medicines = medicines;
@XoseLluis
XoseLluis / awaitAvoidsStackOverflow.js
Last active October 3, 2021 18:04
Usina await to avoid stack overflows in recursive functions (works both for tail and not tail recursion)
const smallValue = 100;
const mediumValue = 1000;
const largeValue = 50000;
function factorial(n) {
//return (n !== 0) ? n * factorial(n - 1) : 1;
if(n === 0 || n === 1){
return 1;
}
else{
@XoseLluis
XoseLluis / trampolineFactory.js
Created October 2, 2021 13:08
Trampoline factory to use with Non Tail Recursion
let st = "helloworld";
//normal recursive (non tail recursion) function
function recursiveTransformString (source){
if (source.length === 0)
return "";
if (source.length === 1)
return source.toUpperCase() + source;
@XoseLluis
XoseLluis / ixjs.AsyncIterableTest.js
Created May 9, 2021 14:37
Leveraging ixjs AsyncIterable to apply sync and async functions via map, filter...
import { from as asyncIterableFrom } from 'ix/asynciterable/index.js';
import { filter as asyncFilter, map as asyncMap } from 'ix/asynciterable/operators/index.js';
function asyncSleep(interval){
return new Promise(resolveFn => setTimeout(resolveFn, interval));
}
async function findCountryForCityAsync(city){
let countries = [
{
@XoseLluis
XoseLluis / joinJavaScriptArrays.js
Last active December 19, 2020 11:23
Join JavaScript arrays (like a DB join)
//sort of inner join
//improved version where we directly obtain the alias from the parameter name in the selector functions
function joinCollectionsImproved(collection1, collection2, idSelectorFn1, idSelectorFn2){
let getAlias = selectorFn => selectorFn.toString().split("=>")[0].trim();
let [alias1, alias2] = [idSelectorFn1, idSelectorFn2].map(getAlias);
let result = [];
collection1.forEach(it1 => {
let id1 = idSelectorFn1(it1);
@XoseLluis
XoseLluis / syncInspectPromise2.js
Created September 8, 2020 20:31
Another way to implement Synchronous Inspection for Promises (as the one provided by bluebird) Not using Inheritance this time, just a new Promise chained to the original one.
//returns a new Promise expanded with inspection methods
function enableSyncInspect(pr){
//we trap these variables in the closure making them sort of private, and allow public access only through the inspection methods that we add to the new promise
let isFulfilled = false;
let value = null; //resolution result
let isRejected = false;
let reason = null; //rejection reason
let isPending = true;
@XoseLluis
XoseLluis / syncInspectPromise.js
Last active September 8, 2020 20:26
Experiment to implement Synchronous Inspection for Promises as the one provided by bluebird. Use Inheritance for it.
//Implement Synchronous Inspection like the one provided by bluebirdjs
//http://bluebirdjs.com/docs/api/synchronous-inspection.html
class SyncInspectPromise extends Promise{
constructor(executorFn){
//compiler forces me to do a super call
super(() => {});
this._isFulfilled = false;
this._value = null; //resolution result
@XoseLluis
XoseLluis / MethodComposition.js
Created August 23, 2020 10:08
Method Composition in JavaScript
function composeMethods(...methods){
//use a normal function, not an arrow, as we need "dynamic this"
return function(...args) {
methods.forEach(method => {
let methodArgs = args.splice(0, method.length);
method.call(this, ...methodArgs);
})
}
}
@XoseLluis
XoseLluis / retryAsyncFunction.js
Created August 2, 2020 13:27
Retry and async function (a function that returns a Promise)
//wrap setTimeout with an async-await friendly function
function sleep(ms){
console.log("sleep starts");
let resolveFn;
let pr = new Promise(res => resolveFn = res);
setTimeout(() => {
console.log("sleep ends");
resolveFn();
}, ms);
return pr;
@XoseLluis
XoseLluis / CancellableAsyncFunction.js
Created June 25, 2020 20:23
Allowing cancellation in an async function
//helper function to use in the async function containing multiple async calls
function checkCancelation(cancelationToken){
if (cancelationToken && cancelationToken.reject){
console.log("throwing");
throw new Error("Rejection forced");
}
if (cancelationToken && cancelationToken.cancel){
console.log("cancelling");
//return a Promise that never resolves
return new Promise(()=>{});