handleClickOutside(event) {
if (myRef && !myRef.current.contains(event.target)) {
alert('You clicked outside of me!');
}
}
const [ selected, setSelected ] = useState({});
const onChange = ({ target: { value, dataset: { id } } }) => {
setSelected({ ...selected, [id]: value });
};
return (
<div>
{data.map(({ id, name, variants }) => (
<div>
<div>{name}</div>
<select
value={selected[id]}
data-id={id}
onChange={onChange}
>
<option>ну давай, выбери что-нибудь</option>
{variants.map(n => <option value={n.price}>{n.data.period}</option>)}
</select>
<div>{selected[id] || 'НИЧЕГО НЕ ВЫБРАНО'}</div>
</div>
))}
</div>
);
Object.values(data.reduce((acc, n) => {
(acc[n.code] ||= {
code: n.code,
name: n.name,
variants: [],
}).variants.push(n);
return acc;
}, {}))
var time = "10:25";
var duration = 1232 ;
const hour = Math.floor(duration / 60);
const min = duration - hour * 60;
let hs = parseInt(time.split(":")[0]);
let ms = parseInt(time.split(":")[1]);
let he = (hs + hour + Math.floor((min+ms)/60))%24;
let me = (min+ms)%60;
alert(`${hour}:${min} - ${he}:${me}`)
hours * 60 + minutes
, например для 10:25 будет 10 * 60 + 25.const hours = Math.floor(finishTime / 60) % 24;
const minutes = finishTime % 60;
const initTime = '10:25',
duration = 1232;
const [initHour, initMin] = initTime.split(':');
const calc = parseInt(initHour)*60 + parseInt(initMin) + 1232;
let hour = Math.floor(calc/60); let hourSave = hour;
if (hour > 23) hour -= 24; //ну или если перелет вдруг больше суток еще условия
const min = calc - (hour < hourSave ? hourSave : hour) * 60;
console.log(`${initTime} - ${hour}:${min}`);
const minSalary = Math.min(...employeeData.map(({ salary }) => salary));
minSalaryEmployee = employeeData.filter(({ salary }) => {
return salary === minSalary;
});
const [id, oldSalary] = [
minSalaryEmployee[0].id,
minSalaryEmployee[0].salary,
];
const newSalary = oldSalary + (oldSalary / 100) * 20;
return { id: id, salary: newSalary };
ибо тут твориться полная жесть...const minSalary = Math.min(...employeeData.map(({salary}) => salary));
const minSalaryEmployee = employeeData.find(({salary}) => salary === minSalary);
const {id, salary: oldSalary} = minSalaryEmployee;
const newSalary = oldSalary + (oldSalary / 100) * 20;
return {id, salary: newSalary};
то сразу можно увидеть простор для оптимизации поиска минимума:const [minSalaryEmployee] = employeeData.reduce(([minEmployee, minSalary], employee) => {
const {salary} = employee;
return (salary < minSalary
? [employee, salary]
: [minEmployee, minSalary]
);
}, [null, Infinity]);
А заодно и формулуconst newSalary = oldSalary + (oldSalary / 100) * 20;
применив алгебру за 5 класс можно упростить доconst newSalary = oldSalary * 1.2;
function increaseSalary() {
return api.getEmployees()
.then(employeeData => {
const [minSalaryEmployee] = employeeData.reduce(([minEmployee, minSalary], employee) => {
const {salary} = employee;
return (salary < minSalary
? [employee, salary]
: [minEmployee, minSalary]
);
}, [null, Infinity]);
const {id, salary: oldSalary} = minSalaryEmployee;
const newSalary = oldSalary * 1.2;
return {id, salary: newSalary};
})
.then(({id, salary}) => api.setEmployeeSalary(id, salary))
.then(({name, id, salary}) => api.notifyEmployee(id, `Hello, ${name}! Congratulations, your new salary is ${salary}!`))
.catch(e => api.notifyAdmin(e));
}
import api from 'path/to/api';
export function increaseSalary() {
return api.getEmployees()
.then(findEmployeeWithMinSalary)
.then(calculateNewSalary)
.then(setEmployeeSalary)
.then(notifyEmployee)
.catch(notifyAdmin);
}
function findEmployeeWithMinSalary(employeeData) {
const [minSalaryEmployee] = employeeData.reduce(minSalaryEmployeeReducer, [null, Infinity]);
return minSalaryEmployee;
}
// Complexity is 3 - это самая сложная функция
function minSalaryEmployeeReducer([minEmployee, minSalary], employee) {
const {salary} = employee;
return (salary < minSalary
? [employee, salary]
: [minEmployee, minSalary]
);
}
function calculateNewSalary({id, salary}) {
return {
id,
salary: salary * 1.2
};
}
function setEmployeeSalary({id, salary}) {
return api.setEmployeeSalary(id, salary);
}
function notifyEmployee({name, id, salary}) {
return api.notifyEmployee(id, `Hello, ${name}! Congratulations, your new salary is ${salary}!`);
}
function notifyAdmin(e) {
return api.notifyAdmin(e);
}
function increaseSalary() {
return new Promise((resolve, reject) => {
let minSalaryEmployee = Promise.resolve().then((employeeData) => {
return { };
});
minSalaryEmployee
.then((data) => {
let newSalary = Promise.reject();
newSalary
.then((newData) => {
resolve(`Ok`);
})
.catch((e) => {
reject(`Error`)
});
})
.catch(reject);
});
}
increaseSalary()
.then(console.log)
.catch(console.error);
function getUsersInfo(ids, callback) {
const {length} = ids;
const results = Array(length);
let doneCount = 0;
ids.forEach((id, i) => {
getUserInfo(id, user => {
results[i] = user;
doneCount++;
if(doneCount === length) {
callback(result);
}
});
});
}
function getUsersInfo(ids, callback) {
const results = [...Array(ids.length)];
ids.forEach((n, i) => {
getUserInfo(n, user => {
results[i] = user;
if (results.every(Boolean)) {
callback(result);
}
});
});
}
let getData = (attempts) => {
if (attempts < 1) {
return Promise.reject('Max attempts reached.');
}
return new Promise((res, rej) => {
console.log('Attempt to fetch data: #' + attempts);
attempts == 1
? setTimeout(() => {res('This is my data')}, 3000)
: setTimeout(() => {rej('Shit happens')}, 3000);
}).catch(e => {
return getData(attempts - 1);
})
}
getData(3)
.then(r => console.info('=> ' + r))
.catch(e => console.error(e));
class BroadcastEventEmitter extends EventEmitter {
emit(event, ...args) {
if (event === '*') {
Object.keys(this.events).forEach((e) => super.emit(e, ...args));
} else {
super.emit(event, ...args);
}
}
}