Giter VIP home page Giter VIP logo

sv443 / jslib-npm Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 1.0 496 KB

This npm package makes coding a bit faster by providing many advanced pre-built functions

Home Page: https://npmjs.com/package/svjsl

License: MIT License

JavaScript 100.00%
download-file javascript javascript-library library miscellaneous miscellaneous-functions miscellaneous-utilities multi-purpose network node-module nodejs npm npm-package

jslib-npm's Introduction

Hi there, I'm Sven

I am a 22 year old full stack developer from Germany.
My interests are in open source software, server and web development, as well as PC and server hardware and IT infrastructure.
Most of my projects are made with or for Javascript, Linux and Arduino.
Although I love working in a familiar environment, I'm always open to try out new technologies and want to continue learning and improving my skills.

What I'm currently working on:

  • JokeAPI is an API that serves a good variety of uniformly formatted jokes and offers lots of filtering methods.
  • BetterYTM, a userscript that brings tons of features and UX improvements to YouTube Music.
  • geniURL, an API for looking up and filtering song metadata from genius.com
  • Userscript.ts, a Template for making Userscripts in TypeScript with tons of modern utilities and comfort features.
  • SvCoreLib, which is a Node.js package that is used in basically all of my JavaScript projects. It contains many miscellaneous features.

My projects are free and open source so I rely on donations to keep my servers and domains running.
So if you like what I do, please consider supporting my development.

If you want to reach out to me, you can join my Discord server or send me an E-Mail.
Please don't contact me with any job offers or shady business requests, you will be ignored.



Links: Homepagenpm

jslib-npm's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar stickler-ci avatar sv443 avatar

Stargazers

 avatar

Watchers

 avatar

jslib-npm's Issues

[Bug] "jsl.pause()" doesn't unregister events -> leads to "stacking" line breaks

If jsl.pause() is used multiple times in the same process, due to the process.stdin.on("data") event not being unregistered, the callback and line breaks will be called multiple times, increasing by one each time jsl.pause() is used.
This might also result in the wrong callbacks being executed at the wrong time, causing bugs that are horrible to debug.

Example code:

let allFlags = ["nsfw", "religious", "political", "racist", "sexist"];

let flagIteration = idx => {
    if(idx >= allFlags.length)
        return flagIterFinished();
    else
    {
        jsl.pause(`Is this joke ${allFlags[idx]}? (y/N):`).then(key => {
            if(key.toLowerCase() == "y")
                joke["flags"][allFlags[idx]] = true;
            else joke["flags"][allFlags[idx]] = false;

            return flagIteration(++idx);
        }).catch(err => {
            console.error(`Error: ${err}`);
            return process.exit(1);
        });
    }
};

flagIteration(0);

Results in:

image

Function to make Array readable

jsl.readableArray(array, separators, lastSeparator)

var array = [1, 2, 3, 4, 5, 6];
jsl.readableArray(array, ", ", "and") // returns "1, 2, 3, 4, 5 and 6"

[Feature] Function that removes duplicates from an array

/**
 * Removes duplicate items in an array
 * @param {Array<*>} array An array with any values that can be compared with the [strict equality comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness)
 * @returns {Array<*>}
 */
function removeDuplicates(array) {
    return array.filter((a, b) => array.indexOf(a) === b);
}

[Feature] Improve handling of two separate "package.json" files (for GPR and NPM)

Instead of having to update both files separately, just have a script generate the GPR-compatible package.json file automatically just before publishing the package to GPR.

  1. Rename "package.json" to "package-npm.json"
  2. Set the needed properties for GPR to accept the publish:
    • "publishConfig": {
          "registry": "https://npm.pkg.github.com/@Sv443"
      }
    • "name": "@sv443/svjsl"
  3. Write the modified properties to "package.json"

[Feature] Pause function that waits for user keypress

/**
 * Waits for the user to press a key and then calls the function passed in `callFunction`
 * @param {Function} callFunction
 */
function pauseThenCall(callFunction, text)
{
    process.stdout.write(`${text} `);
    process.stdin.resume();

    let keypressEvent = chunk => {
        if(process._jslPtcListenerAttached)
        {
            process.stdin.pause();
            removeKeypressEvent();

            // CTRL+C has to exit the process:
            if(chunk && chunk.match(/\u0003/gmu)) //eslint-disable-line no-control-regex
                return process.exit(0);

            return callFunction();
        }
    };

    let removeKeypressEvent = () => {
        process.stdin.removeListener("keypress", keypressEvent);
        process._jslPtcListenerAttached = false;
    };

    process.stdin.on("keypress", keypressEvent);
    process._jslPtcListenerAttached = true;
}

Progress bar class

Code:

/**
 * Creates a dynamic progress bar with a percentage and custom message display
 * @param {Number} timesToUpdate How many times you will call ProgressBar.next() in total - example: 4 means you will need to call ProgressBar.next() exactly four times to reach 100% progress
 * @param {String} [initialMessage=""] Initial message that appears at 0% progress
 * @since 1.7.0
 */
const ProgressBar = class {
    constructor(timesToUpdate, initialMessage) {
        if(initialMessage == undefined) initialMessage = "";
        this.timesToUpdate = timesToUpdate;
        this.iteration = 1;
        this.progress = 0.0;
        this.progressDisplay = "";
        this.filledChar = "■";
        this.blankChar = "─";
        this.finishFunction = undefined;

        for(let i = 0; i < this.timesToUpdate; i++) this.progressDisplay += this.blankChar;

        this._update(initialMessage);
    }

    /**
     * Increment the progress bar. The amount of these functions should be known at the point of initially creating the ProgressBar object.
     * @param {String} message Message that should be displayed
     */
    next(message) { // increments the progress bar
        this.progress = (1 / this.timesToUpdate) * this.iteration;

        let pt = "";
        for(let i = 0; i < this.iteration; i++) pt += this.filledChar;
        this.progressDisplay = pt + this.progressDisplay.substring(this.iteration);
        
        this._update(message);
        this.iteration++;
    }

    _update(message) { // private method to update the console message
        if(this.iteration <= this.timesToUpdate) {
            if(message != "" && message != undefined) message = "- " + message;
            process.stdout.cursorTo(0);
            process.stdout.clearLine();
            process.stdout.write(`${(this.progress != 1.0 ? "\x1b[33m" : "\x1b[32m")}\x1b[1m${Math.round(this.progress * 100)}%\x1b[0m ${(Math.round(this.progress * 100) < 10 ? "  " : (Math.round(this.progress * 100) < 100 ? " " : ""))}[${this.progressDisplay.replace(new RegExp(this.filledChar, "gm"), "\x1b[32m\x1b[1m" + this.filledChar + "\x1b[0m")}] ${message}${(this.progress != 1.0 ? "" : "\n")}`);
            if(this.progress == 1.0 && this.finishFunction != undefined) this.finishFunction();
        }
    }

    /**
     * Executes a function once the progress reaches 100%
     * @param {Function} callback Function
     */
    onFinish(callback) {
        if(typeof callback != "function" || callback == undefined || callback == null) throw new Error("Wrong arguments provided for ProgressBar.onFinish() - (expected: \"Function\", got: \"" + typeof callback + "\")");
        this.finishFunction = callback;
    }

    /**
     * Get the current progress as a float value
     * @returns {Float}
     */
    getProgress() {
        return this.progress;
    }

    /**
     * Get the amount of increments that are still needed to reach 100% progress
     * @returns {Number}
     */
    getRemainingIncrements() {
        return (this.timesToUpdate - this.iteration >= 0 ? this.timesToUpdate - this.iteration : 0);
    }
}

Usage:

var pb = new ProgressBar(7, "Initializing...");
var ct = 0;

setInterval(()=>{
    pb.next("SomeMessage" + (ct + 1));
    ct++;
}, 1000);

pb.onFinish(()=>process.exit(0));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.