Sep 02, 2021
Disposable Functions
Since I like to use this term (but never found any other source with that wording) I want to describe what a disposable function means to me:
- a lambda-helper-function, which is only invoked inside another function
- is only accessible inside a specific function
With the following benefits:
- helps to avoid code repetition
- describes what it does by its name (cleaner code)
- avoids creating private functions when they are only used exclusively inside one function
Example
function createSerialNumber() {
let randomString = (length, charPool = 'ABCDEFGHJKLMPQRTUVWXYZ346789') => {
return Array(length).fill(0).map(() => {
return charPool[Math.floor(Math.random() * charPool.length)];
}).join('');
}
// Example result: '6YFR-444EPP-3CAB8-3371'
return `${randomString(4)}-${randomString(6)}-${randomString(5)}-${randomString(4,'346789')}`;
}
In this example, the disposable function is randomString
. It's used here four times to create a random String in different length and characters to build a serial number.