Skip to content

Instantly share code, notes, and snippets.

@ahmad-511
Last active April 25, 2023 05:24
Show Gist options
  • Save ahmad-511/79f62262e96113225ddddd9f7b4c848f to your computer and use it in GitHub Desktop.
Save ahmad-511/79f62262e96113225ddddd9f7b4c848f to your computer and use it in GitHub Desktop.
General JS utility functions
// #1 Select first matched element
export function $(selector, elem) {
elem = elem || document;
return elem.querySelector(selector);
}
// #2 Select all matched elements
export function $$(selector, elem) {
elem = elem || document;
return elem.querySelectorAll(selector);
}
// #3 Singular to plural
export function plural(word, count){
if(count < 2){
return word;
}
word = word.toString();
const vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
let suffix = 's';
let lastLetter = word.substr(-1, 1);
const isUpperCase = (lastLetter == lastLetter.toUpperCase());
lastLetter = lastLetter.toLowerCase();
if(lastLetter == 'y'){
const beforeY = word.substr(-2, 1);
if(vowels.indexOf(beforeY) > -1){
suffix = 's';
}else{
word = word.substr(0, word.length-1);
suffix = 'ies';
}
}else if(['x', 's'].indexOf(lastLetter) > -1 ){
suffix = 'es';
}
return word + (isUpperCase?suffix.toUpperCase(): suffix);
}
// #4 Convert input string with new-line characters to HTML br
export function nl2br(str) {
str = str || '';
return str.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n/g, '<br>');
}
// #5 Convert input string with new-line characters to HTML paragaphs
export function nl2p(str) {
str = str || '';
return '<p>' + str.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n/g, '</p><p>') + '</p>';
}
// #6 Reseting a form, used mostly for hidden fields as they don't get affected by form.reset() method
export function resetForm(form){
// Normal reset
form.reset();
// Set elements with data-default attribte to the specified value
$$('input[data-default]', form).forEach(elem => {
elem.value = elem.dataset.default;
});
}
// #7 Event emitter, used to emit custom events to all subscribed listeners
export class EventEmitter {
listeners = [];
emit(eventName, ...data){
for(let {callback} of this.listeners.filter(l => l.name == eventName)){
return callback(...data);
}
}
listen(name, callback){
this.listeners.push({name, callback});
}
remove(eventName){
this.listeners = this.listeners.filter(({name}) => name != eventName);
}
}
/* --------- #3 Singular to plural example --------- */
import {plural} from './utils.js';
console.log(1, plural('file', 1))
console.log(2, plural('file', 2))
/* --------- #7 Event Emitter example, Machine engine --------- */
import {EventEmitter} from './utils.js';
class Machine {
event = new EventEmitter();
start(engineName, startAfter = 1){
// Simulate processing
setTimeout(() => this.event.emit('EngineStarted', engineName, new Date()), startAfter)
}
stop(engineName, stopAfter = 1){
// Simulate processing
setTimeout(() => this.event.emit('EngineStopped', engineName, new Date()), stopAfter)
}
}
const machine1 = new Machine();
// Listen for EngineStarted and EngineStopped events on machine1
machine1.event.listen('EngineStarted', (engineName, dt) => {
console.log(`[${engineName}] engine started on ${dt}`)
// Starting the auxiliary engine after 2 seconds of main engine get started
if(engineName == 'main'){
machine1.start('auxiliary', 2000)
}
})
machine1.event.listen('EngineStopped', (engineName, dt) => {
console.log(`[${engineName}] engine stopped on ${dt}`)
// Stopping the auxiliary engine after 2 seconds of main engine get stopped
if(engineName == 'main'){
machine1.stop('auxiliary', 2000)
}
})
// More events can be added as needed and the emitter will call them all in the same sequence they're added to
// Listen for EngineStarted and EngineStopped events on machine1 (to perform additional steps)
machine1.event.listen('EngineStarted', (engineName, dt) => {
console.log(`Turning on [${engineName}] engine's light bulb`)
})
machine1.event.listen('EngineStopped', (engineName, dt) => {
console.log(`Turning off [${engineName}] engine's light bulb`)
})
// Perform some action on machine1 which will emit related events
machine1.start('main', 1000)
machine1.stop('main', 6000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment