Jump to content

Welcome to Xbox-Vibes

Sign In Register

Recommended Posts

  • xModerator

In this topic i want to share with you my codes which can be usefull for someone (maybe). So have a fun!

First of all let's have fun with matrices! 🙂

Usage:

Create matrix: let sampleMatrice = new Matrix([25, 11], [23, 11, 45], [13]);

[] means array of matrix items as rows

Transparent matrix: sampleMatrice = sampleMatrice.transparent(); - will return a new instance of Matrix object, so rememeber about asserting to variable!

Calculate any diagonals with: sampleMatrice.getDiagonalToLeft(rowIndexStart, columnIndexStart), sampleMatrice.getDiagonalToRight(rowIndexStart, columnIndexStart) and reversed.

Calculate main determinant: sampleMatrice.calculateMainDeterminant();

Code Version 1:

 

 

Hide?Collapse Text

Javascript:
class Matrix {
    _accessor = [];
    constructor() {
        let matrixMaxRowsLen = 0;
        try {
            for(let matrixRow in arguments) {
                if(Array.isArray(arguments[matrixRow])) matrixMaxRowsLen = Math.max(matrixMaxRowsLen, arguments[matrixRow].length);
            }
            for(let matrixRow in arguments) {
                let matRow = new Array(matrixMaxRowsLen).fill(0);
                for(let j = 0;j<arguments[matrixRow].length;j++) matRow[j] = arguments[matrixRow][j];
                this._accessor.push(matRow);
            }
        } catch(MatrixError) {
            console.error(MatrixError);
        }
    }
    getItem(indexRow, indexColumn) {return this._accessor[indexRow][indexColumn]}
    setItem(newValue, indexRow, indexColumn) {
        try {
            if(!isNaN(parseFloat(newValue))) this._accessor[indexRow][indexColumn] = parseFloat(newValue); else throw "Matrix items must be a number or number convertable value!";
        } catch(MatrixError) {
            console.error(MatrixError);
        }
    }
    getRow(indexRow) {return this._accessor[indexRow];}
    getColumn(indexColumn) {
        let column = [];
        for(let matrixRow in this._accessor) column.push(this._accessor[matrixRow][indexColumn]);
        return column;
    }
    transparent() {
        let transparented = [];
        for(let i = 0;i<this._accessor.length;i++) transparented.push(this.getColumn(i));
        return new Matrix(...transparented);
    }
    getDiagonalToRight(fromRowIndex=0, fromColumnIndex=0, customAccessor=null) {
        if(customAccessor==null) customAccessor = this._accessor;
        let outputRow = [];
        for(let matrixRow in customAccessor) {
            for(let matrixColumn in customAccessor[matrixRow]) {
                if(matrixRow==fromRowIndex && matrixColumn==fromColumnIndex) {
                    outputRow.push(customAccessor[matrixRow][matrixColumn]);
                    fromRowIndex++;
                    fromColumnIndex++;
                }
            }
        }
        return outputRow;
    }
    getDiagonalToLeft(fromRowIndex=0, fromColumnIndex=-1, customAccessor=null) {
        if(customAccessor==null) customAccessor = this._accessor;
        if(fromColumnIndex<0) fromColumnIndex = this.columnLength - 1;
        let outputRow = [];
        for(let matrixRow in customAccessor) {
            for(let matrixColumn = customAccessor[matrixRow].length - 1;matrixColumn>=0;matrixColumn--) {
                if(matrixRow==fromRowIndex && matrixColumn==fromColumnIndex) {
                    outputRow.push(customAccessor[matrixRow][matrixColumn]);
                    fromRowIndex++;
                    fromColumnIndex--;
                }
            }
        }
        return outputRow;
    }
    getDiagonalRevesedToLeft(fromRowIndex=-1, fromColumnIndex=-1) {
        if(fromRowIndex<0) fromRowIndex = this.rowLength - 1;
        if(fromColumnIndex<0) fromColumnIndex = this.columnLength - 1;
        let outputRow = [];
        for(let matrixRow = this._accessor.length - 1;matrixRow>=0;matrixRow--) {
            for(let matrixColumn = this._accessor[matrixRow].length - 1;matrixColumn>=0;matrixColumn--) {
                if(matrixRow==fromRowIndex && matrixColumn==fromColumnIndex) {
                    outputRow.push(this._accessor[matrixRow][matrixColumn]);
                    fromRowIndex--;
                    fromColumnIndex--;
                }
            }
        }
        return outputRow;
    }
    calculateMainDeterminant() {
        let fromLeftSum = 0, fromRightSum = 0, combinedAccessor = [...this._accessor, ...this._accessor];
        if(this._accessor.length>2) {
        for(let matrixRow in this._accessor) {
            fromLeftSum += this.getDiagonalToRight(matrixRow, 0, combinedAccessor).reduce((prev, next)=>prev*next);
            //console.log(fromLeftSum);
            fromRightSum += this.getDiagonalToLeft(matrixRow, -1, combinedAccessor).reduce((prev, next)=>prev*next);
            //console.log(fromRightSum);
        }
        } else { fromLeftSum = this.getDiagonalToRight(0, 0, combinedAccessor).reduce((prev, next)=>prev*next); fromRightSum = this.getDiagonalToLeft(0, -1, combinedAccessor).reduce((prev, next)=>prev*next); }
        return fromLeftSum - fromRightSum;
    }
    get lastRow() {return this._accessor[this._accessor.length - 1];}
    get lastColumn() {return this.getColumn(this.columnLength);}
    get rowLength() { let len = 0; for(let matrixRow in this._accessor) len = Math.max(len, this._accessor[matrixRow].length); return len; }
    get columnLength() {return this._accessor.length}
    get length() {return this.columnLength * this.rowLength;}
    toString() {
        let outputStr = "", totalLen;
        for(let matrixRow in this._accessor) totalLen = Math.max(totalLen, this._accessor[matrixRow].join(" ").length);
        for(let matrixRow in this._accessor) {
            outputStr += '|';
            for(let matrixColumn in this._accessor) {
                let repeater = (totalLen/this._accessor[matrixRow].length)-this._accessor[matrixRow][matrixColumn].length;
                outputStr += `${"".repeat(repeater)}${this._accessor[matrixRow][matrixColumn]}${"".repeat(repeater)}`;
            }
            outputStr += '|\n';
        }
        return outputStr;
    }
}

 

 

 

Github: https://github.com/Grano22/MathAdv.js

 

Link to comment
Share on other sites

  • 3 weeks later...
  • Replies 2
  • Created
  • Last Reply
  • xModerator

Next is format function (popular in many technologies and programming languages). So i made it for you in JS!

 

Source (Repository): https://github.com/Grano22/jumper/blob/master/dataProcessing.js

Usage in current version: format(targetStr: string, initialObject: Array<any> || Object.prototype);

Example: format("Hello %s exacly! Wow, we make it %d times!", ["World", 14]);

Output: "Hello World exacly! Wow, we make it 14 times!"

Example #2: format("Thats really simple with %s[labelsWord], you can use it in any %s[situationWord]!", {labelsWord:"labels", situationWord:"situation"});

Output: "Thats really simple with labels, you can use it in any situation!"

 

Raw:

Hide?Collapse Text

function format(targetStr, initialObj=null) {
    try {
        let sequences = [], sequence = "", inVarDeclaration = false, outputStr = "", fParams = [];
        for(let charn in targetStr) {
            if(targetStr.hasOwnProperty(charn)) {
            if(!inVarDeclaration && (typeof targetStr[charn - 1]=="undefined" || targetStr[charn - 1]!="\\") && targetStr[charn]=="%" && targetStr[parseInt(charn) + 1].trim()!="") {
                inVarDeclaration = true;
            } else if(inVarDeclaration && targetStr[charn]=="[") {
                if(!["s", "n", "b", "a", "f", "d"].includes(sequence)) throw "Unknown type given in format "+sequence+" at position "+charn;
                fParams.push(sequence);
                sequence = "";
            } else if(inVarDeclaration && targetStr[charn]=="]") {
                fParams.push(sequence);
                sequences.push(fParams);
                sequence = "";
                inVarDeclaration = false;
                fParams = [];
            } else if(inVarDeclaration && (targetStr[charn].trim()=="" || targetStr.length - 1<=parseInt(charn))) {
                if(targetStr.length - 1<=parseInt(charn)) sequence += targetStr[charn];
                if(sequence.indexOf("[")>-1) throw "Format proeprty name cannot have a whitespace";
                if(!["s", "n", "b", "a", "f", "d"].includes(sequence)) throw "Unknown type given in format "+sequence+" at position "+charn;
                fParams.push(sequence);
                sequences.push(fParams);
                sequence = "";
                inVarDeclaration = false;
                fParams = [];
            } else if(inVarDeclaration && targetStr[charn]!="[" && targetStr[charn]!="_" && !(targetStr[charn].charCodeAt()>=65 && targetStr[charn].charCodeAt()<=90) && !(targetStr[charn].charCodeAt()>=97 && targetStr[charn].charCodeAt()<=122)) throw "Invaild symbol "+targetStr[charn]+" at position "+charn;
            else if(inVarDeclaration) sequence += targetStr[charn];
            }
        }
        outputStr = targetStr;
        let currItem = null;
        for(let catched in sequences) {
            if(Array.isArray(sequences[catched])) {
                if(sequences[catched].length>0) {
                    currItem = sequences[catched].length>1 ? initialObj[sequences[catched][1]] : initialObj[catched];
                    if(typeof currItem!="undefined" && currItem!=null) {
                    switch(sequences[catched][0]) {
                        case "s":
                            if(typeof currItem!="string") currItem = currItem.toString();
                            outputStr = outputStr.replace(sequences[catched].length>1 ? "%"+sequences[catched][0]+"["+sequences[catched][1]+"]" : "%"+sequences[catched][0], currItem);
                        break;
                        case "sr":
                            if(typeof currItem!="string") throw "positional argument "+catched+" requires type string";
                            outputStr = outputStr.replace(sequences[catched].length>1 ? "%"+sequences[catched][0]+"["+sequences[catched][1]+"]" : "%"+sequences[catched][0], currItem);
                        break;
                        case "f":
                            if(!(Number(currItem) === currItem && currItem % 1 !== 0)) { currItem = parseFloat(currItem); }
                            outputStr = outputStr.replace(sequences[catched].length>1 ? "%"+sequences[catched][0]+"["+sequences[catched][1]+"]" : "%"+sequences[catched][0], currItem);
                        break;
                        case "d":
                            if(!(Number(currItem) === currItem && currItem % 1 === 0)) currItem = parseInt(currItem);
                            outputStr = outputStr.replace(sequences[catched].length>1 ? "%"+sequences[catched][0]+"["+sequences[catched][1]+"]" : "%"+sequences[catched][0], currItem);
                        break;
                        case "b":
                            if(typeof currItem!="boolean") currItem = !!currItem;
                            outputStr = outputStr.replace(sequences[catched].length>1 ? "%"+sequences[catched][0]+"["+sequences[catched][1]+"]" : "%"+sequences[catched][0], currItem);
                        break;
                    }
                    }
                } else throw "Cannot parse format due to lack of type at index "+catched+" (function format error)";
            } else throw "Cannot parse format due to invaild sequence type at index "+catched+" (function format error)";
            currItem = null;
        }
        return outputStr;
    } catch(FormatingError) {
        console.error(FormatingError);
    }
}

 

 

Link to comment
Share on other sites

  • xModerator

New version of Jumper package is available. Now you can parse HTML strings into React elements/components and native elements.

Just look (React): https://codesandbox.io/s/jumper-module-react-simple-parser-3b8c9?file=/src/App.js

Repository (Source): https://github.com/Grano22/jumper/blob/master/components.js

Newest NPM Package: https://www.npmjs.com/package/jumper_react

 

Next version will contains iterable keys - objects in format functions and also new types and more on components (widgets).

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • Create New...