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 / extendProxyHandler.js
Created November 22, 2016 00:33
Determine if an ES6 object is a proxy
function extendProxyHandler(handler){
let originalGetTrap = handler.get;
handler.get = function(target, propKey, receiver){
switch (propKey){
case "_isProxy":
return true;
break;
case "_proxyTarget":
return target;
break;
@XoseLluis
XoseLluis / typedSerializerES6.js
Created January 27, 2017 18:14
Typed Serialization in javascript
function getFunctionFromStringName(functionNameSt){
eval("var func = " + functionNameSt + ";");
return func;
}
class TypedSerializer{
static serialize(obj){
let aux = {
typeName: obj.constructor.name,
data: obj
@XoseLluis
XoseLluis / MixinsCompositionAndInheritance.js
Created February 1, 2017 00:12
Example of Mixin composition and inheritance in ES6
function printPrototypeChain(obj){
let protoNames = [];
let curProto = Object.getPrototypeOf(obj);
while (curProto){
protoNames.push(curProto.constructor.name);
curProto = Object.getPrototypeOf(curProto);
}
console.log("prototype chain:\n" + protoNames.join("."));
}
function addMethodMissingCapabilityToClass(classConstructor, manageMissingItem){
let _proto = classConstructor.prototype;
classConstructor.prototype = new Proxy(_proto, {
get: function(target, key, receiver){
//console.log("get trap invoked");
if (key in target){
return target[key];
}
else{
@XoseLluis
XoseLluis / PromiseWorkerHelper.js
Created August 6, 2018 14:25
Web Wroker returning a Promise. Sort of .Net Task.Run
class PromiseWorkerHelper{
constructor(){
//one shot object, we create it and invoke its run method just once
this.alreadyCalled = false;
//this.worker = new Worker("WebWorkerCode.js");
this.worker = this._createWorkerFromString();
//this is executed when the worker posts a message
this.worker.onmessage = (msg) => this.resolveFunc(msg.data);
@XoseLluis
XoseLluis / modifiableProxy.js
Created February 20, 2019 20:17
Creating JavaScript proxies that can be modified (replace the get trap logic)
function modifiableProxyFactory(target){
//initialize the proxy with a "transparent" trap
let coreGetTrapFunc = (target, property, receiver) => target[property];
let handler = {
//the "get trap" checks if we want to set the trap, otherwise it invokes the existing trap
get: function(target, property, receiver){
if (property === "setGetTrap"){
console.log("setting a new get trap!");
return function(getTrap){
coreGetTrapFunc = getTrap;
@XoseLluis
XoseLluis / proxiesAndImmutability.js
Last active April 14, 2019 13:56
Create an immutable wrapper (that allows cloning and modification by means of set_XXX methods) around and existing object: https://deploytonenyures.blogspot.com/2019/04/immutability-via-proxies.html
function createImmutable(item){
let handler = {
set: function(target, property, value){
//do nothing, this object is no longer "directly" mutable
console.log("hey, I'm immutable, you can't set me like this");
},
//object is mutable only by invoking a "set_XXXX" method
//we trap that get and return a function that will create the new object with the mutated property
//and returns a proxy around the new object, so that immutability continues to work in ensuing assignments
@XoseLluis
XoseLluis / usingObservables.ts
Created June 28, 2019 16:54
Promises vs Observables comparison for functions returning single data (not a data stream)
import { Observable, Subject, ReplaySubject, from, of, range, observable } from 'rxjs';
import { map, flatMap, filter, concatMap, switchMap, delay, tap } from 'rxjs/operators';
function getUserId(userName:string, callback: (id:number) => void){
let users: { [key: string]: number } = {
anonymous: -1,
francois: 1,
chloe: 2
};
setTimeout(() => callback(users[userName] as number), 2000);
@XoseLluis
XoseLluis / AsyncCallsThrottling.js
Last active December 3, 2019 23:06
Throttiling async calls
class TicketProvider{
constructor(maxActiveTickets){
this.activeTickets = 0;
this.maxActiveTickets = maxActiveTickets;
this.waitingTickets = []; //array of resolve function, to get invoked once we have a free slot, so the code waiting for the ticket can move on
}
//returns Promise<void>
getTicket(){
if (this.activeTickets<this.maxActiveTickets){
@XoseLluis
XoseLluis / privatizeMethod.ts
Last active August 14, 2019 15:49
Privatize a JavaScript (TypeScript) method at runtime
function calledFromInsideClass(className:string):boolean{
let stackTrace = (new Error()).stack; // Only tested in latest FF and Chrome
//console.log("stackTrace: " + stackTrace);
stackTrace = (stackTrace as string).replace(/^Error\s+/, ''); // Sanitize Chrome
let callerLine = stackTrace.split("\n")[2]; // 1st item is this function, 2nd item is the privatizedMethod, 3rd item is the caller
return callerLine.includes(className + ".");
}
function privatizeMethod(classFn: any, methodName: string){