Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions js-core/homeworks/telephone/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home work 1</title>
</head>
<body>

<script src="src/main.js"></script>
</body>
</html>
126 changes: 126 additions & 0 deletions js-core/homeworks/telephone/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*Приложение телефонный справочник

Создайте функцию конструктор.
У данной функции должны быть методы:

1+. Преобразование телефонного номера из формата 0993378130 в (099) 33-78-130
2+. Проверка, что телефонный номер содержит только числа
3+. Добавление пользователей в справочник
4+. Удаление пользователя по имени, фамилии
5+. Поиск пользователей по имени - отображает всех пользователей с одинаковым именем
6+. Изменение имени, фамилии, телефонного номера у выбраного пользователя ( здесь должно быть реализовано через this )
7+. Сортировка пользователей по номеру телефона, фамилии, имени и тд, по любому из свойств пользователя
8. Фильтр по указанному свойству

*/
const myApp = new PhoneApp();

function PhoneApp() {
this.dataBase = [
{ id: 1, name: 'Vasya', phone: '1234' },
{ id: 2, name: 'Vasya2', phone: '12441' },
{ id: 5, name: 'Vasya5', phone: '12444' },
{ id: 6, name: 'Vasya6', phone: '12444' },
{ id: 7, name: 'Vasya2', phone: '12442' },
{ id: 8, name: 'Vasya2', phone: '12443' },
{ id: 9, name: 'Vasya2', phone: '12455' }
]
}
PhoneApp.prototype.phoneNum = function(phoneNum) {
if (this.testOnNum(phoneNum) && this.ten(phoneNum)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (!this._isPhoneNumberValid) {
 return `неправильно введен номер`
};

let str = phoneNum;
return `(${str.substring(0,3)}) ${str.substring(3,5)}-${str.substring(5,7)}-${str.substring(7,10)}`;

let str = phoneNum;
return `(${str.substring(0,3)}) ${str.substring(3,5)}-${str.substring(5,7)}-${str.substring(7,10)}`;
} else {
return `неправильно введен номер`;
}
}
PhoneApp.prototype.testOnNum = function(phoneNum) {
let arr = phoneNum.split('');
let isNum = function(number) {
return !isNaN(number);
}
return arr.every(isNum);
}
PhoneApp.prototype.ten = function(phoneNum) {
return phoneNum.length == 10 || `введите десятизначный номер`;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please verify it works as expected

}
PhoneApp.prototype.addUser = function(name, phone) {
let lastId = this.dataBase[this.dataBase.length - 1].id;
let obj = {};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

еще один конструктор для пользователя

obj.id = lastId + 1;
obj.name = name;
obj.phone = this.phoneNum(phone);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если у пользователя будет не верный номер, тогда ему запишется строка неправильно введен номер
И не факт что это будет лучше, я бы сказал что лучше хотя бы null передавать

this.dataBase.push(obj);
}
PhoneApp.prototype.deleteUser = function(name) {
this.dataBase.forEach((value, i) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use .filter instead of .forEach

if (value.name == name) {
this.dataBase.splice(i, 1);
}
});
}
PhoneApp.prototype.search = function(name) {
let arr = [];
this.dataBase.forEach((value, i) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please user .filter

if (value.name == name) {
arr.push(value);
}
});
return arr;
}
PhoneApp.prototype.change = function(name, newName, newPhone) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

имя метода change мало понятно, change что ?

changeUser ? но это тоже не совсем правда этот метод может что-то изменить, а может и не изменить :)

Тут можно не бояться длинных названий, это будет более информативно. Явное всегда лучше неявного

if (newName && newPhone) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот тут лучше записать

if( !(newName && newPhone) ) {
  return
}
this.changePhone(name, newPhone);
this.changeName(name, newName);

this.changePhone(name, newPhone);
this.changeName(name, newName);
}
}
PhoneApp.prototype.changeName = function(name, newName) {
this.dataBase.forEach((value, i) => {
if (value.name == name) {
this.dataBase[i].name = newName;
}
});
}
PhoneApp.prototype.changePhone = function(name, newPhone) {
this.dataBase.forEach((value, i) => {
if (value.name == name) {
this.dataBase[i].phone = this.phoneNum(newPhone);
}
});
}
PhoneApp.prototype.sort = function(param) {
//let tempArr = this.dataBase
return this.dataBase.sort((a, b) => {
return a[param] > b[param];
});
}
PhoneApp.prototype.filter = function(str) {
let dataBaseFilter = [];
this.dataBase.forEach((value, i) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь точно нужно использовать .filter. Правильный выбор метода перестроит этот код верно

это может выглядеть например таким образом

.filter(user => {
let userFields = Object.values(user);
return userFields.some(userData => userData.includes(str))
})

Этот пример еще нужно доработать в твоем примере более сложные вещи вот тут:

value[key].length - str.length
value[key].substr(j, str.length) == str
dataBaseFilter.push(value);
return;

Почему этот код мне не нравится, потому что если в дальнейшем его нужно будет дорабатывать, большая вероятность что нужно будет переписать все.
И если ты посмотришь на этот код например даже через месяц, будет сложно понять что тут происходит

for (let key in value) {
for (let j = 0; j <= value[key].length - str.length; j++) {
if (value[key].substr(j, str.length) == str) {
dataBaseFilter.push(value);
return;
}
}
}
});
return dataBaseFilter;
}

console.log(myApp.phoneNum('1234567890'));
console.log(myApp.testOnNum('1234567890'));
myApp.ten('1234567890');
myApp.addUser('alex', '0671233445');
myApp.addUser('alex1', '5554618456');
//console.log(myApp.deleteUser('Vasya2'));
//console.log(myApp.deleteUser('alex'));
console.log(myApp.search('Vasya2'));
myApp.changeName('alex', 'Alexey');
myApp.change('Vasya6', 'Pedro', '3333333333');
myApp.changePhone('Pedro', '2222222222');
console.log(`dataBase `, myApp.dataBase);
console.log(`dataBase `, myApp.sort('name'));
//console.log(`dataBase `, myApp.sort('id'));
console.log(`filter `, myApp.filter('ex'));