# Interview
## Task 1
What is wrong?

## Task 2
File
```
const helper = require('@mongoHelper');
module.exports = async (botId, entityId) => {
const bot = await helper.Bot.findOne({ botId });
const entity = await helper.Entity.findOne({ entityId });
const project = await helper.Project.findOne({ projectId: bot.projectId });
return { bot, entity, project };
};
```
## Task 3
```
const config = { template: { a: { v: 1 } } };
const { template: { a: org } } = config;
const { template: { a: copy } } = config;
org.v+=1;
console.log(org.v) => 2
console.log(copy.v) =>
console.log(config.template.a.v) =>
```
## Task 4
Write function to check if number is prime
```
function isPrimeNumber(number) {
}
isPrimeNumber(7) => true
isPrimeNumber(16) => false
isPrimeNumber(121) => false
isPrimeNumber(17) => true
```
## Task 5
Write function to check if array is sorted
isSorted([1,2,5,7,34]) => true
isSorted([1,56,2,5,7,34]) => false
isSorted([4,3,2,1]) => true
```
```
## Task 6
Write next function
Input: aaabbcdaa
Output:
3 a
2 b
1 c
1 d
2 a
```
```
## Task 7
Write next function
Input: 2 5 4 6
Output:
4 5 6
2 8 10 12
3 12 15 18
4 16 20 24
5 20 25 30
## Task 8
```
const types = [
{ id: 1, name: 'type-1' },
{ id: 2, name: 'type-2' },
{ id: 3, name: 'type-3' }
];
// const enumTypes = {
// 'type-1': 1,
// 'type-2': 2,
// 'type-3': 3
// }
```
## Task 9
```
function intersection(a, b) {
}
```
intersection([1,2,3], [2,3,5]) => [2,3]
## Task 10
distinct([1,2,3,4,1,2,2,4,-6]) => [1,2,3,4,-6]
```
function distinct(arr) {
}
```
## Task 11
```
const arr =[]
(req, res, next) => {
const isStarted = process.env
arr.push(req)
if(isStarted) next(arr)
}
app.get('/sessions', middleware, handlers.getSessions);
app.get('/sessions/:sessionId', handlers.getSessions.byId);
app.listen(3000);
dbConnect().then(async () => {
const config = await helper.SystemConfig();
setSystemConfig(config);
process.env.isOnline = 'true';
// app.on('service-online', () => {})
app.emit('service-online');
})
```
## Task 12
```
users = { _id, userId, email, password };
tasks = { _id, taskId, userId, content, expirationDateTime };
```
1. Написать запрос, который будет возвращать всех пользователей в которых таски
```
```
3. Написать запрос, который будет возвращать всех пользователей в которых таски, не заекспайрилися
```
```
5. Написать запрос, который будет возвращать все таски которые не заекспайрилися, вместе с пользователями, которым они принадлежат
```
```
7. Написать запрос, который будет возвращать список пользователей в которых заэкспайрился все таски
```
```
## Task 13
Create API route for creating and updating task object in DB. Task object:
```
{
taskId: number, // this field will be created by DB
userId: number,
name: string,
notes: string[],
}
```
post: /tasks body: { userId, name }
put: /tasks/:taskId body: { name, notes }
Function for DB:
* helper.task.create(data) - this function creating object and return Promise
* helper.task.updateOne(query, data) - this function updating object and return Promise
* helper.task.find(query)
```
const express = require('express');
const app = express();
app.listen(3000);
```
## Task 14
```
const handler = (cb) => {
helper.Entity.findOne(
{ entityId: 45 },
(err,data)=> {
if (err) { return cb(err); }
helper.FileEntity.find(
{ ownerEntityId: data._id },
(err, files) => {
if (err) { return cb(err); }
return cb(null, { entities: data, files })
}
)
}
)
}
```
## Task 15
Create report with first 5 session what was in [167, 392]. Get entity docs for each entity who are in session and get types names.
Collection sessions:
```=json
{
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c5"),
"allowPosting" : {
"roleIds" : [ ],
"entityIds" : [ ]
},
"conversationFlow" : [
"directMessaging"
],
"nextStep" : [ ],
"isFake" : false,
"isActive" : true,
"updatedAt" : ISODate("2021-05-06T11:46:07.000Z"),
"settings" : {
"endSessionMessage" : {
"isEnabled" : false,
"platforms" : [ ]
},
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c4")
},
"lastMessageDateTime" : ISODate("2021-05-06T11:46:07.552Z"),
"workspaceId" : 167,
"typeId" : 0,
"sessionTtl" : 31536000000,
"entities" : [
{
"isInitiator" : false,
"originalEntityIds" : [ ],
"isMute" : false,
"isRemoved" : false,
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c6"),
"entityId" : 329162,
"platformId" : 8,
"platformConnectorId" : "5dfc1d5e0bba7a000729aea0"
},
{
"isInitiator" : true,
"originalEntityIds" : [ ],
"isMute" : false,
"isRemoved" : false,
"_id" : ObjectId("6093d4c3cdf9a3000a7cb5c7"),
"entityId" : 809540,
"platformId" : 8,
"platformConnectorId" : "5dfc1d5e0bba7a000729aea0"
}
],
"instanceId" : "00c61b117c0aedd9e59e512a9456b92e5fd9f0d78f74ed0cbc3f9dfa167d15b12d1f025f9e37a6ef2b9c1e33b5cbfecb5bc353bf5d26592f51a2335eee5ccdd4b34ce006ce40ebcc",
"startDateTime" : ISODate("2021-05-06T11:36:35.996Z"),
"expirationDateTime" : ISODate("2022-05-06T11:46:08.735Z"),
"sessionId" : 496004,
"__v" : 2,
"messagesCount" : 2
},
```
Collection entities:
```=json
{
"_id" : ObjectId("609283eccdf9a3000a7cb13d"),
"platformPriority" : [ ],
"organizationIds" : [
3
],
"entityTypeIds" : [
0
],
"email" : "kkarpp@gmail.com",
"lastName" : "Karp",
"firstName" : "Customer neew",
"phoneNumber" : "+xxxxxxxxxxxx",
"createdAt" : ISODate("2021-05-05T11:39:24.980Z"),
"updatedAt" : ISODate("2021-05-05T11:39:24.981Z"),
"entityId" : 809664,
"__v" : 0
},
```
Collection entityTypes:
```=json
{
"_id" : ObjectId("5b69f25984d8e645dcdb7396"),
"entityTypeId" : 4,
"isMergeEligible" : false,
"name" : "Rake System User"
},
```
Result:
```=json
{
"_id" : ObjectId("5dfc1d80f2bc5500075f5b81"),
"sessionId" : 13654,
"sessionStatus" : true,
"entities" : [
{
"_id" : ObjectId("5cda74e83f9e1f0006c3827a"),
"entityId" : 2007,
"entityTypes" : [
"Rake System User"
],
"name" : "Oleh2Buhaienko"
}
]
},
```
# Task 16
```
const transform = (str) => {
const [event, valueArr] = str.split('_')
const eventValues = valueArr.split('-')
if(eventValues.length === 1){
return {
event, value: eventValues[0]
}
return {
event, value: eventValues}
}
transform('message-watcher_1979-3452') => { event: 'message-watcher', value: [1979, 3452] }
transform('sessions-inactivity_1995') => { event: 'session-inactivity', value: 1995 }
```
# Task 17
RegExp
"Session with id {{sessionId}} has ended. Agent name: {{agentName}}"
```
const transform = (str, tokens) => {
}
const message= { text: "Session with id {{sessionId}} has ended. Agent name: {{agentName}}" };
const tokens = {
sessionId: 56,
agentName: 'Max',
sentAt: '2021-05-07T11:43:31.836Z'
};
const text = transform(message.text, tokens);
```
# Task 18
Options:
- Move validation to middleware
- Use Joi modules
```
app.post('/user', (req,res) => {
const { email, password } = req.body;
if (!email) {
return res.sttus(400).send({ message: 'Email is required' });
}
if (!password) {
return res.sttus(400).send({ message: 'Password is required' });
}
return handler.createUser(req, res);
})
```
# Task 19
Request logger
```
app.get('/users/:userId', async (req,res) => {
const user = await helper.Users.findOne({ userId: + req.params.userId});
return res.status(200).send(user);
})
```
Output:
```
[req:ffda1464-c39c-11eb-8529-0242ac130003][path:/users/56][method:get]
[req:ffda1464-c39c-11eb-8529-0242ac130003][time:2.3s] response: { userId: 56, firstName: 'FN', lastName: 'LN' }
```
# Task 20
```
{
firstName: String,
lastName: String,
email: String
}
```
> Can we remove any indexes?
index_1: { firstName: 1 }
index_2: { lastName: 1 }
index_3: { email: 1, lastName: 1 }
index_4: { email: 1, lastName: 1, firstName: 1 }
index_5: { lastName: 1, firstName: 1 }
index_6: { email: 1, firstName: 1 }
index_7: { email: 1, firstName: 1, lastName: 1 }
> What index will used?
model.findOne({ firstName }) =>
model.findOne({ firstName, lastName }) =>
model.findOne({ email, lastName }) =>
model.findOne({ lastName, firstName }) =>
# Task 21
Convert array to tree
```
const systemFunctions = [
{ systemFunctionId: 46, parentId: null, },
{ systemFunctionId: 56, parentId: 46 },
{ systemFunctionId: 1, parentId: 2 },
{ systemFunctionId: 2, parentId: null },
{ systemFunctionId: 3, parentId: null, },
{ systemFunctionId: 4, parentId: 3 },
{ systemFunctionId: 5, parentId: 4, },
{ systemFunctionId: 6, parentId: 4, },
{ systemFunctionId: 7, parentId: 4, },
{ systemFunctionId: 25, parentId: -9, },
{ systemFunctionId: 26, parentId: 25, },
{ systemFunctionId: 27, parentId: 26, },
];
const toTree = (data) => {
...
}
```
```=javascript
const result = [
{
systemFunctionId: 46,
parentId: null,
childs: [
{ systemFunctionId: 56, parentId: 46 },
]
},
{
systemFunctionId: 2,
parentId: null,
childs: [
{ systemFunctionId: 1, parentId: 2 },
]
},
{
systemFunctionId: 3,
parentId: null,
childs: [
{
systemFunctionId: 4,
parentId: 3,
childs: [
{ systemFunctionId: 5, parentId: 4, },
{ systemFunctionId: 6, parentId: 4, },
{ systemFunctionId: 7, parentId: 4, },
]
},
]
},
{
systemFunctionId: 25,
parentId: -9,
childs: [
{
systemFunctionId: 26,
parentId: 25,
childs: [
{ systemFunctionId: 27, parentId: 26 },
]
},
]
},
]
```