forked from urfu-2015/javascript-tasks-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphoneBook.js
82 lines (70 loc) · 2.23 KB
/
phoneBook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
var phoneBook = []; // Здесь вы храните записи как хотите
var spaceReplace = new RegExp(' ', 'g');
var mailTest = new RegExp('^[^@]+@[^@]+\.[^@]+$', 'ig');
module.exports.add = function add(name, phone, email) {
if (checkName(name) && checkPhone(phone) && checkMail(email)) {
phoneBook.push({name: name, phone: formatPhone(phone), email: email});
}
};
function formatPhone(phone) {
phone = phone.replace(spaceReplace, '');
phone = phone.replace(/\(/, '');
phone = phone.replace(/\)/, '');
phone = phone.replace(new RegExp('-', 'g'), '');
return phone;
}
function checkName(name) {
return name && typeof name === 'string';
}
function checkPhone(phone) {
if (typeof name !== 'string' || phone === '') {
return false;
}
phone = phone.replace(spaceReplace, '');
if ((/\(/.test(phone) && !/\)/.test(phone)) || (!/\(/.test(phone) && /\)/.test(phone))) {
return false;
}
var regExpr = new RegExp('^\\+?(\\d{1,3})?\\(?\\d{3}\\)?(\\d{3}-?\\d-?\\d{3})$', 'g');
return regExpr.test(phone);
}
function checkMail(email) {
return email && typeof email === 'string' && mailTest.test(email);
}
function search(query) {
if (query === '') {
return phoneBook;
}
var result = [];
var regExpr = new RegExp(query);
for (var i = 0; i < phoneBook.length; i++) {
var entry = phoneBook[i];
if (regExpr.test(entry.name) || regExpr.test(entry.email) || regExpr.test(entry.phone)) {
result.push(entry);
}
}
return result;
}
module.exports.find = function find(query) {
var i;
var found = search(query);
for (i = 0; i < found.length; i++) {
console.log(found[i]['name'] + ', ' + found[i].phone + ', ' + found[i].email);
}
};
module.exports.remove = function remove(query) {
var i;
var j = 0;
var found = search(query);
for (i = 0; i < found.length; i++) {
while (j < phoneBook.length) {
var entry = phoneBook[i];
if (entry === found[i]) {
phoneBook.splice(i, 1);
} else {
j++;
}
}
}
console.log('Удалено контактов:', found.length);
};