Keywords.js 🚀
A lightweight, zero dependency package to make custom keywords!
Yes you understood that right, custom keywords! Well not real keywords, but emulated ones. This packge does it by defining global getters and setters.
The no-argument keywords look very natural.
For example you can implement die
or use the computed propery style
die; // process.exit(0) for Node.js or throw new Error("exited") for Browsers myComputedProperty; // Calls your function and returns anything you want
The argument-taking keywords look more weird. because of they are setters you need to use the assignment (=
) operator to invoke the keyword. It looks more keywordy when you split the keyword name and the =
sign (e.g save= value
instead of save = value
). Even more, setters can't return a custom value, so you have to use the comma (,
) operator and the __value
global variable.
For example let's imagine a save
keyword which takes an argument.
save= myValue // Invokes your function and passes "myValue" in save= myValue __value // Does the same, but returns the value you returned from your function
Thats the theory, lets dive in to practice!
Installation 💿
npm i keywordsjs
for NodeJS
<script src="https://cdn.jsdelivr.net/npm/keywordsjs@latest/keywords-browser.min.js"></script>
for browsers.
Documentation 🔍
Well, this package is pretty easy, so some commented examples are enought to understand how it works.
// Defining the "die" keyword const Keywords = ; // For Node.js Keywords someCode...die; // This will work
Using the state API
Keywords forlet i = 0; i < 10; i++ console;// 0, 1, 2, 3... 9
You can dynamically attach and detach keywords:
const justdoitKeyword = Keywords justdoit // works // Removes the keywordjustdoitKeyword; // OR Keywords.detach(`justdoit`) justdoit // Error: justdoit not defined // Puts it backjustdoitKeyword; justdoit // works
Multiple defining and detaching is also supported
Keywords Keywords // Multiple attaching not supported
Defining argument-taking keywords
Keywords let array = 1 2 3;reverse= array;console; // [3, 2, 1]
Defining multiple-argument-taking keywords is also possible, using arrays
Keywords let arrays = 123 456 789;reverse= arrays;console; // [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Returning values from argument-taking-keywords
Keywords tohex= 365 // returns 365tohex= 365 __value // returns your value, but it's not usedconst hex = tohex= 365 __value // returns your value and it's used
That's it, Thanks!