Last active
November 3, 2021 22:43
-
-
Save salodev/130b8c313041a718ecd3472e10deb82c to your computer and use it in GitHub Desktop.
A fancy 'wich' keyword alternative in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Hello everyone! | |
// | |
// I want to bring an idea that I guess.. maybe useful for you. | |
// | |
// With no more words, we will ride into the concept. | |
// Suppose an scenario like following: | |
let result = | |
this.a.lot.of.dot.levels.myAim.methodA() + | |
this.a.lot.of.dot.levels.myAim.methodB() + | |
this.a.lot.of.dot.levels.myAim.methodC(); | |
// Surely you don't want repeat many times same path to reach your target object. | |
// So, a simple way may be next: | |
let myAim = this.a.lot.of.dot.levels.myAim; | |
let result = | |
myAim.methodA() + | |
myAim.methodB() + | |
myAim.methodC(); | |
// But, what about 'wich' syntax?. It is not allowed for strict mode, plus ambiguity contras.. | |
// So, we can do it another way much better ellegant: Creating our own 'wich' syntax. | |
// Lets do it called 'context' because unlike 'wich', our new syntax just creates a context where put our code. | |
// First at all, let's imagine how can we write the final code: | |
let result = context(this.a.lot.of.dot.levels.myAim, (aim) => { | |
let result = | |
aim.methodA() + | |
aim.methodB() + | |
aim.methodC(); | |
return result; | |
}); | |
// So, seems some cool and fancy. | |
// Now, what the context() function does? Ok, let's ride into initial definition: | |
function context(aim, fn: (v) => any): any { | |
return fn(v); | |
} | |
// Well,sounds good.. But what about if we need put async calls into callback scope, and need await it outside scope? | |
// Ok, again, fist of all we'll see implementation: | |
let result = await context(this.a.lot.of.dot.levels.myAim, async (aim) => { | |
let result = | |
(await aim.methodA()) + // the async call | |
aim.methodB() + | |
aim.methodC(); | |
return result; | |
}); | |
// It simply will work because the context function is returning a 'Promise<any>' | |
// result so its call can be awaited. | |
// Now, for a more complete context() definition, take next code: | |
function context<T = any, R = any>(v: T, fn: (w:T) => any): R { | |
return fn(v); | |
} | |
// As we can see, it is a very simple and fancy solution | |
// that can help us to save a bit or lots of KB of our sourcecode, | |
// writing less and doing more.. | |
// | |
// Happy coding, I hope you gets a good day.. Bye bye! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment