//SORT

var persons = [
    {name: "Иван", age: 17},
    {name: "Мария", age: 35},
    {name: "Алексей", age: 73},
    {name: "Яков", age: 12},
]

function sort(arr, type, bool = true) {
    return arr.sort((a, b) => {
        let res;
        if (bool) {
            console.log('true')
            res = a[type] > b[type] ? 1 : -1;
        } else {
            console.log('false')
            res = a[type] < b[[type]] ? 1 : -1;
        }
        return res
    })
}
console.log(sort(persons, 'name', false))


//ARRAY MAP
let someArr = ["1", {}, null, undefined, "500", 700];

let newArr = someArr.map(item => typeof item === 'string' ? +item : item)
console.log(newArr)


//ARRAY REDUCE
let reduceArr = ["0", 5, 3, "string", null];
let reducedArr = reduceArr.filter(item => typeof item === 'number').reduce((acc, curr) => acc *= curr)
console.log(reducedArr)


//OBJECT FILTER
var phone = {
    brand: "meizu",
    model: "m2",
    ram: 2,
    color: "black",
};

function filter(obj, callback) {
    let filteredObj = {}
    for(let key in obj) {
        if (callback(key, obj[key])) {
            filteredObj = {...filteredObj, [key]: obj[key]}
        }
      }
        return filteredObj
}

console.log(filter(phone,(key,value) => key === "color" || value === 2))


//OBJECT MAP
function map(obj, callback) {
    let res = {};
    for(let key in obj) {
        res = { ...res, ...callback(key, obj[key]) }
    }
    return res
}

let test = map({name: "Иван", age: 17},function(key,value){
    var result = {};
    result[key+"_"] = value + "$";
    return result;
})
console.log(test)


//SUM
function geomProgressionCalc(min, max, step){
    if (max <= 0) return 0;
    return geomProgressionCalc(min + step,max -1, step) + min
}

console.log(geomProgressionCalc(10, 20, 2))

//HTML TREE RECURSION
let $table = document.createElement('table');

function rerenderColor(e, color) {
    Array.from($table.children).map(item => {
        Array.from(item.children).filter(item => item.cellIndex === e.target.cellIndex).map(item => item.style.backgroundColor = color)
    })
};

let i = 10;
function createRow() {
    i--
    let $tr = document.createElement('tr')

    let j = 1;
    function createCell() {
        j++
        let $td = document.createElement('td');
        $td.innerText = String(j * i)
        $td.addEventListener('mouseover', (e) => {
            rerenderColor(e, 'red')
            $td.style.backgroundColor = 'green'
        })
        $td.addEventListener('mouseout', (e) => rerenderColor(e, 'transparent'))
        $tr.appendChild($td)
        if(j < 9) createCell()
    }
    $table.appendChild($tr)
    createCell()
    if(i > 1) createRow();
}

createRow()
document.body.appendChild($table);