Coder Social home page Coder Social 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%
javascript javascript-library npm npm-package library miscellaneous miscellaneous-utilities miscellaneous-functions nodejs node-module network download-file multi-purpose

jslib-npm's Introduction

JSLib Banner


This project now has a new home - https://github.com/Sv443/SvCoreLib is a continuation of this library




JSLib (npm) by Sv443

A multi-purpose, lightweight and dependency-free JavaScript library that makes coding faster by providing many easy to use functions and classes
MIT License build coverage Snyk Vulnerabilities

GitHub watchers GitHub stars




Installation:

Enter this in your command line to download JSLib:

npm i svjsl

Then, import it in your script like this:

const jsl = require("svjsl");





These are some of the features JSLib offers:

> Create a dynamic, interactive menu prompt directly in the command line:

Menu Prompt


> Or create a progress bar:

Progress Bar


> Other features include:

  • Download files from the internet
  • Generate random numbers based on a seed (same input seed = same numbers every time)
  • Transform numbers to other numerical ranges
  • Add some color to your console output
  • Generate UUIDs with many pre-built numerical systems and even custom ones

...and many more! You can check out the full list here.







If you need any help, feel free to join my Discord server and I will help you as soon as possible:

Discord Invite



Made with ❤️ by Sv443
Support me on Patreon, Ko-fi or PayPal

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

[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));

[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);
}

[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] 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"

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.