forked from urfu-2015/javascript-tasks-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phone-book.js
94 lines (81 loc) · 2.66 KB
/
phone-book.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
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
var phoneBook = [];
function UserData(name, phone, email) {
this.name = name;
this.phone = phone;
this.email = email;
}
module.exports.add = function add(name, phone, email) {
if (isDataCorrect(name, phone, email)) {
phoneBook.push(new UserData(name, phone, email));
console.log('** Запись ' + name + ' добавлена');
return true;
} else {
console.log('** Невозможно добавить запись. Запись ' + name + ' некорректна.\n');
return false;
}
};
function isQueryInData (currentContact, query) {
query = query.toLowerCase();
for(var propetry in currentContact) {
if (currentContact[propetry].toLowerCase().indexOf(query) > -1) {
return true;
}
};
return false;
}
function findIndexes(query) {
var goodIndexes = [];
phoneBook.forEach(function (item, i, phoneBook) {
if (isQueryInData(item, query)) {
goodIndexes.push(i);
};
});
return goodIndexes;
};
module.exports.find = function find(query) {
query = query || '';
if (query === '') {
for (var i = 0; i < phoneBook.length; i++) {
printLine(i);
};
} else {
var indexes = findIndexes(query);
for (var item = 0; item < indexes.length; item++) {
printLine(indexes[item]);
};
}
};
module.exports.remove = function remove(query) {
query = query || '';
var indexes = findIndexes(query);
indexes = indexes.reverse();
for (var i = 0; i < indexes.length; i++) {
phoneBook.splice(indexes[i], 1);
};
console.log('** Удален(ы) ' + indexes.length + ' контакта(ов)\n');
};
module.exports.importFromCsv = function importFromCsv(filename) {
var data = require('fs').readFileSync(filename, 'utf-8');
var counter = 0;
data = data.split('\n');
for (var i = 0; i < data.length; i++) {
var tmp = data[i].split(';');
if (module.exports.add(tmp[0], tmp[1], tmp[2])) {
counter++;
};
};
console.log('** Импортировано ' + counter + ' контактов из ' + filename + '.\n');
};
module.exports.showTable = function showTable(filename) {
};
function printLine(index) {
console.log(phoneBook[index].name +
', ' + phoneBook[index].phone +
', ' + phoneBook[index].email);
}
var PHONE_REGEXP = /^\+?\d{1,11} ?-?((\(\d{3}\))|(\d{3})) ?-?\d{1,3} ?-?\d{1,3} ?-?\d{1,3}$/;
var EMAIL_REGEXP = /^\w*\@[\-a-zA-Zа-яА-Я]+(\.[\-a-zA-Zа-яА-Я]{2,})+$/;
function isDataCorrect(name, phone, email) {
return EMAIL_REGEXP.test(email) && PHONE_REGEXP.test(phone);
};