Stateful Purgatory

by Renoir Boulanger

HTML

<script>
console.log('hi!')

const defaultKeyValidator = (key) => typeof key === 'string' || typeof key === 'number';
class StatefulPurgatory {
    constructor(keyValidator = defaultKeyValidator) {
        this.keyValidator = keyValidator;
        this.timerMap = new Map();
        this.expiredKeys = new Set();
        /**
         * Make something we want to keep track of to be self-purging.
         * I.e. keep track of keys, by telling you've used them, if after a time isn't used, fill a list
         *
         * Thank you: https://github.com/kricha/debounce-with-map
         */
        this.setDebounce = (fn, delay = 1000) => {
            if (this.honk) {
                throw new Error(`It is best NOT to set this method twice`);
            }
            this.honk = (key) => {
                if (!key) {
                    throw Error('You need to set a key');
                }
                if (this.keyValidator(key) === false) {
                    throw Error(`This key "${key}" did not match key format validation, refer to this instance’s keyValidator method`);
                }
                ;
                ((...args) => {
                    // Start by checking if there's still an item in the timerMap
                    // i.e. something that we're still checking, we're going to check, right now.
                    let timeOutId = this.timerMap.get(key);
                    if (timeOutId) {
                        // We’ll set another timeoutId for that one, carry on.
                        window.clearTimeout(timeOutId);
                    }
                    // If we don't set window.setTimeout, it would use NodeJS’
                    // In the case of setTimeout would return NodeJS.Timeout
                    timeOutId = window.setTimeout(() => {
                        // Call that function
                        // Probably make that function aware of this instance's expired getter keys TBD
                        fn(...args);
   ...