Let's look on the example of some database:
We have fields "id", "destination" (where to fly), date of creation, author name, hashtags and flight.
var posts = [
{
id: '1',
destination: 'China',
createdAt: new Date(2014, -1, 1, 2, 3, 4, 567),
author: 'ChingHang',
hashTags:['Berlin'],
flug: 'A-730'
},
{
id: '2',
destination: 'Italien',
createdAt: new Date(2014, -1, 1, 2, 3, 4, 567),
author: 'PetrovPetr',
hashTags:['Minsk'],
flug: 'A-733'
},
{
id: '3',
destination: 'Spanien',
createdAt: new Date(2017, 0, 1, 2, 3, 4, 567),
author: 'IvanovaKatya',
hashTags:['Moskau'],
flug: 'A-777'
},
{
id: '4',
destination: 'Griechenland',
createdAt: new Date(2013, 0, 1, 2, 3, 4, 567),
author: 'ZaicevVasiliy',
hashTags:['Riga'],
flug: 'A-321'
},
];
The code above - our structure of masses to keep information structured.
Then we make a class, where all functions will be initialized and will be connected with our structure.
class arbeit {
(functions)
constructor(posts) {
this._posts=posts;
}
}
Getting posts with the filter (author)
getPosts(skip=0,top= 10, filterConfig){
if(filterConfig!=undefined){
let result = posts.filter(team => team.author === filterConfig.author)
return result.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(skip,skip+top);
}
else {
return posts.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(skip,skip+top);
}
}
Getting post with id
getPost(id) {
for (var i = 0; i < posts.length; i++) {
if (posts[i].id === id) {
return posts[i];
}
}
throw "No object with " + id + " id";
}
Validating object
validatePost(Object){
return Object.id != null && Object.destination != null && Object.destination.length<400
&& Object.author != null && Object.createdAt != null && typeof Object.id === "string" && typeof Object.destination === "string" && typeof Object.flug === "string"
&& typeof Object.author === "string"
}
Clearing our "database"
clear(){
posts.splice(0,posts.length);
}
Adding a new post
addPost(Object){
if(this.validatePost(Object)){
posts.splice(posts.length,0,Object);
return true;
}
else {
return false;
}
}
Editing post
editPost(id,post){
if(this.validatePost(post)){
this.getPost(id).destination=post.destination;
this.getPost(id).author=post.author;
return true;
}else {
return false;
}
}
Removing post
removePost(id){
for (var i = 0; i < posts.length; i++) {
if (posts[i].id === id) {
return posts.splice(i,1);
}
}
throw "No object with " + id + " id";
}
Explanation of these functions I will make in another article. Follow me for updates.
Good luck in your job!
Written by Yuri Filatov, IT Expert at Andersen