jollyKuma
9/24/2017 - 11:18 AM

optimize

optimize

const ratings = [
    { rating: 5 },
    { rating: 2 },
    { rating: 0 },
    { rating: 1 },
    { rating: 4 },
    { rating: 3 },
    { rating: 5 }
];

const maxRate = 5;

const ratingLazyMap = function *(ratings, mapFunction) {
    for (elem of ratings) {
        yield mapFunction(elem);
    }
};

const genStarChar = (target, num, char) => {
    for (let i = 1; i <= num; i++ ) {
        target.push(char);
    }
    return target;
}

const mapRatings = (elem) => {
    elem.rate = [];
    if (elem.rating) {
        const subRate = maxRate - elem.rating;
        if (subRate > 0) {
            elem.rate = genStarChar(elem.rate, elem.rating, ("\u2605").toString(16));
            elem.rate = genStarChar(elem.rate, subRate, ("\u2606").toString(16));
            return elem.rate;
        }
        return elem.rate = genStarChar(elem.rate, maxRate, ("\u2605").toString(16));
    }
    return elem.rate = genStarChar(elem.rate, maxRate, ("\u2606").toString(16));
}

const execGen = (iterator) => {
    const { done, value } = iterator.next();

    if (!done) {
        console.log(value);
        execGen(iterator);
    }
};

const lazyIterator = ratingLazyMap(ratings, mapRatings);

execGen(lazyIterator);