A
A
Alexey2018-03-24 16:53:43
JavaScript
Alexey, 2018-03-24 16:53:43

Check for entry into the range of numbers or if-hell?

How are such checks for occurrence in a certain interval of numbers or dates done correctly?
Let's say there are 500 some events, they have recorded time in unixtime. What is the best way to count and display events for the last 14 days from the current time?
So far I have only one idea

//создаем сразу массив с нужными данными
var datesArray = [];
var currentTime = Date.now;
var i = 13; 
var timeInterval = 86400; //сутки
for(;i--;) {
  datesArray.push( currentTime - timeInterval * i )
};
//и вторым циклом перебирать уже массив событий
i = 0
for(;i < events.length; i++) {
  if (events.time >= datesArray[13] && events.time < datesArray[12] ) {
  //событие было 13 дней назад
  } else if (events.time >= datesArray[12] && events.time < datesArray[11] ) {
  //событие было 12 дней назад
  } else if ( events.time >= datesArray[11] && events.time < datesArray[10] ) {
  //событие было 11 дней назад
  };
//ну и так далее, думаю смысл понятен
}

Is there any more optimal way to do this, and how much performance can drop if there are 10k+ such events?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Immortal_pony, 2018-03-24
@Immortal_pony

moment.js will help you with dates.
Example:

var dates = [1520608921, 1520522534, 1512400948, 1521037358, 1521814967];
var fourteenDaysAgo = moment().subtract(14, 'days').format('X');
var filteredDates = dates.filter(function(date) { 
  return date > fourteenDaysAgo;
});

R
Ruslan., 2018-03-24
@LaRN

Where are you getting these events from?
If from the database, it can be easier to solve it (selection of events by date) at the request level to the database.

E
Eugene, 2018-03-25
@epifanB

I would do something like this:

const events = [
  {id:1, time: 10},
  {id:2, time: 11},
  {id:3, time: 15},
  {id:4, time: 14},
  {id:5, time: 13}
];
const bottom_limit = 11;
const result = events
                .filter( event => event.time >= bottom_limit )
                .sort( (first, second) => first.time - second.time );

> Is there any more optimal way to do this, and how much performance can drop if there are 10k+ such events?
You can use setTimeout, iterate over part of the array at a time ( https://learn.javascript.ru/settimeout-setinterval... or use web workers ( https://developer.mozilla.org/ru/docs/Web/API/Web_ ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question