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 / LazyObjectViaProxy.js
Created June 13, 2020 09:44
Lazy Object via Proxy
//Create a Proxy for the lazy construction of an object
function buildLazyObject(constructorFn, ...args){
let internalObject = null;
//we don't care about the target, but compiler does not allow a null one, so let's pass an "empty object" {}
return new Proxy({}, {
get: function(target, property, receiver){
console.log("this === receiver " + (this === receiver)); //false
//"this" is not the proxy, but the handler object containing the traps (obviously are not the same object)
internalObject = internalObject || (() => {
console.log("Creating object");
//we don't need to inherit from Promise, await works fine with just a "thenable"
//notice in the second part of the code that Promise.resolve of a thenable returns a new Promise rather than the thenable
class LazyPromise {
constructor(creationFn){
console.log("creating LazyPromise");
this.initialized = false;
this.creationFn = creationFn;
}
@XoseLluis
XoseLluis / recursiveTransformString.js
Last active May 17, 2020 17:35
Avoid to overfill the stack, part 2
function transformString (source){
if (source.length === 0)
return "";
if (source.length === 1)
return source.toUpperCase() + source;
let curItem = source[0];
let transformed = transformString(source.substring(1));
return curItem.toUpperCase() + transformed + curItem;
@XoseLluis
XoseLluis / factorialAndTimeout.js
Last active May 17, 2020 17:35
Avoiding to overfill the stack thanks to setTimeout
const smallValue = 100;
const largeValue = 50000;
function factorial(n) {
return (n !== 0) ? n * factorial(n - 1) : 1;
}
function tailFactorial(n, total = 1) {
//console.trace();
if (n === 0) {
@XoseLluis
XoseLluis / AsyncExtendedIterable.js
Last active February 16, 2020 15:17
POC Methods for Async Iterables. A continuation to my previous (lazyIterable) gist: https://gist.github.com/XoseLluis/69ab06d98dad132a36ee1c580e08df1f
const printDebug = (msg) => console.log(msg);
class AsyncExtendedIterable{
constructor(iterable){
this.iterable = iterable;
}
async *[Symbol.asyncIterator](){
for await (let it of this.iterable){
@XoseLluis
XoseLluis / ProxySyncAndAsyncMethods.js
Created January 26, 2020 18:45
Proxying sync and async methods
let calculator = {
simpleCalculation(n){
return 25 * n;
},
complexCalculation(n){
return new Promise(res => {
setTimeout(() => res(44 * n), 3000)
});
},
@XoseLluis
XoseLluis / SortByMultipleCriteria.js
Last active January 26, 2023 20:45
Sort Array by Multiple Criteria
// Factory Function to combine multiple sort criteria
// receives functions representing sorting criteria
// returns a new function that applies these criteria
function sortByMultipleCriteriaFactory(...sortFuncs){
return (it1, it2) => {
for (sort of sortFuncs){
let res = sort(it1, it2);
if (res !== 0){
//for this criteria items are not equal (in sorting terms) so no more criteria to apply
return res;
@XoseLluis
XoseLluis / PromiseAllWithLimit.js
Last active December 4, 2019 21:46
Like Promise.all, but limiting how many functions to run in parallel. https://deploytonenyures.blogspot.com/2019/12/promiseall-with-limit.html
//I'm calling "task" to a function that when executed returns a Promise
class PromiseAllWithLimit{
constructor(tasks, maxItems){
this.allTasks = tasks;
this.maxItems = maxItems;
this.taskResults = [];
this.nextTaskId = 0;
this.resolveAll = null; //points to the resolve function to invoke when all tasks are complete
this.completedCounter = 0;
}
@XoseLluis
XoseLluis / lazyIterable.js
Created November 10, 2019 15:55
Just a POC of how to add deferred-lazy methods to an Iterable. As I've said this is just a POC, for something real go and use lazy.js
class ExtendedIterable{
constructor(iterable){
this.iterable = iterable;
}
*[Symbol.iterator](){
for (let it of this.iterable){
yield it;
}
}
var _ = require('lodash');
class Formatter{
constructor(repetitions){
this.repetitions = repetitions;
}
format1(txt){
return `${"[" .repeat(this.repetitions)} ${txt} ${"]" .repeat(this.repetitions)}`;
}