π Please.js
the polite way of building a javascript util library for your project
Does this sound familiar?
You are building some helper functions for your project, you want to eventually combine it under one name... and now you spend hours thinking about what to call your util library.
This is your problem no more.
Enter:
Create a polite API for whatever you want to build.
You have a function to move an element from a to b? What about this API:
// Politely ask to move something
please.move(element);
You have a function to hide a textbox? What about this API:
// Politely ask to hide content
please.hideTheTextbox('.thisone');
You have a function to have HBO remake the horrible last season of Game of Thrones? What about this API?
// Hey HBO, are you listening?
please.remakeThatNonsens();
Doesn't that all look like a super polite API?
Luckily this all can be yours now, so let me show you how!
Installation and how to use
Add it to your project
npm install @codeb/pleasejs
After that -- import please
where your utility functions live.
// ./please.js
import Please from '@codeb/pleasejs';
// create your new polite please instance
const please = new Please();
//Let's teach it a new method
please.learn('sayHello', (name) => {
console.log(`Hello ${name}`);
});
Now this function is made available to you on the please instance. You could call it like this:
please.sayHello('Wonder Woman');
// -> logs 'Hello Wonder Woman'
What a polite wayway to add new methods. You can add all the methods you want now. So let's see how to make it available in your project:
Expose please to my project
At the end of your own please.js
file you just want to export it, so the rest of your project can politely do things.
export default please;
Import it and use it!
// ./some-file.js
import please from './please.js';
please.sayHello('Batman');
That's it.
One more thing
There's one little thing that I would recommend to do though.
As you've seen it's easy to add new methods to please
, but this also means you could add new methods wherever you have access to the instance. As this is potentially annoying and might put all the awesome code you want to use in too many places, please
got your back.
-
learn
will always warn you if you if there already is method defined with that name.
please.learn('sayHello', () => {});
// -> Throws Error 'Method sayHello is already defined'
- Also, you can freeze your instance to avoid accidental additions and make sure your codebase is polite AND clean.
// Prevent adding any new methods by freezing the API into place
please.freeze();
All together
Here's all the code from above put together clean and simple.
import Please from '@codeb/pleasejs';
const please = new Please();
please.learn('sayHello', (name) => {
console.log(`Hello ${name}`);
});
please.freeze();
export default please;
It was never easier to write a polite utility library.