Показать сообщение отдельно
  #2129 (permalink)  
Старый 22.11.2017, 13:24
Аватар для join
Профессор
Отправить личное сообщение для join Посмотреть профиль Найти все сообщения от join
 
Регистрация: 05.03.2012
Сообщений: 477

Сделал бы так:
const readline = require('readline');
const fs = require("fs");
const Stream = require('stream');

function isTriangle(sides) {
    if (sides.length === 3) {
        return true;
    }
    return false;
    //const a = parseInt(sides[0]), b = parseInt(sides[1]), c = parseInt(sides[2]);
    //return a + b > c && a + c > b && b + c > a;
}

function isSquare(sides) {
    const firstSide = parseInt(sides[0]);
    return sides.length === 4 && sides.every(side => parseInt(side) === firstSide);
}

function isRectangle(sides) {
    return sides.length === 4 && parseInt(sides[0]) === parseInt(sides[2]) && parseInt(sides[1]) === parseInt(sides[3]) && parseInt(sides[0]) !== parseInt(sides[1]) 
}

function getLineStream(filePath) {
    const readFileStream = fs.createReadStream(filePath);
    const outputStream = new Stream();
    return readline.createInterface(readFileStream, outputStream);
}

function getPolygons(lineStream) {
    return new Promise((resolve, reject) => {
        const all = [];
        const triangles = [];
        const squares = [];
        const rectangles = [];
        const others = [];

        lineStream.on("line", set => {
			let sex = set.replace(/[\"|\;]/gm,'').split(",");
            if (isTriangle(sex)) {
                triangles.push(set)
            } else if (isRectangle(sex)) {
                rectangles.push(set);
            } else if (isSquare(sex)) {
                squares.push(set);
            } else {
                others.push(set);
            }

            all.push(set);
        });

        lineStream.on("error", reject);
        lineStream.on("close", () => {
            resolve({all, triangles, squares, rectangles, others});
        })
    })
}

(async function () {
    const {all, triangles, rectangles, others, squares} = await getPolygons(getLineStream("./file.js"));
    console.log(`Triangles ${triangles.join("")}`);
    console.log(`Squares ${squares}`);
    console.log(`Rectangles ${rectangles}`);
    console.log(`Others ${others}`);
    console.log(`All ${all}`);
}());


file.js:
"4,2,3,4";
"2,5,2,5";
"6,6,6,6";
"2,4,6";
"5,12,44,55,44,33";
"4,3";
"7,8,9";
"4,4,4,4";
Ответить с цитированием