scope-extensions-js
Package for using Kotlin's Scope Function Extensions on JavaScript and TypeScript.
It also supports the use of the new Optional Chaining Operator, bringing the logic of Kotlin's Null Safe Calls to the JavaScript world.
Installation
Just install the package using NPM
npm i --save scope-extensions-js
and import it directly to any file.
;
You can also use ES6 syntax.
;
For browser, reference directly to node_modules
path
or use it without installation by CDNs (unpkg
/jsdelivr
).
Note that the type="module"
tag is not needed.
Usage
Simply call any value with let
, also
, run
or apply
and it'll be passed as the argument or the context of a scope function.
; obj.let.also; // prints 30
This way, you can execute a block of code only if a value is neither null nor undefined.
; // laterstr?.also ?? console.log"Still not initialized";
The above code is equivalent to this
if str != null && str != undefined console.log`Already initialized: `;else console.log"Still not initialized";
The usage of takeIf
& takeUnless
is a bit different. You can call any value with takeIf
and it will return the caller instance if the predicate is true
, or undefined
if it's false
(and vice versa when using takeUnless
).
; account.takeIf?.also ?? console.log"Not included";
Differences
We could group the 4 main extensions into 2 groups of 2 each, based on both the argument type and the return value:
let
&also
receive the caller instance as a function parameter, andrun
&apply
receive the caller instance as the function context (this
).let
&run
return the function result (return
) value, andalso
&apply
return the caller instance (this
).
Summed up in this table:
it argument |
this context |
|
---|---|---|
Returns result | let |
run |
Returns this |
also |
apply |
Note that let
& also
can be called with standard lambda/arrow functions, but because JavaScript arrow functions don't have an own this
context, run
& apply
have to be called with standard functions.
Here is an example of each one of them:
let
;
also
; ; // same as;
run
apply
; obj.apply;
License
Copyright © 2020 TheDavidDelta.
This project is MIT licensed.