Round date to the nearest 5 minutes moment as array - arrays

I need to Using a Date() utc , to round a time to the nearest five minutes then push it as array
example:
[
"2019_10_9_00_05",
"2019_10_9_00_10",
"2019_10_9_00_15",
"2019_10_9_00_20",
]
Code
const now = moment();
const time= [];
for (let i = 0; i < 4; i++) {
now.add(5, 'minutes');
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
}
console.log(time);
output
[
"2019_10_9_00_03",
"2019_10_9_00_7",
"2019_10_9_00_11",
"2019_10_9_00_16",
]
any solution's please

You need to check if minutes value is multiple of 5 first.
const now = moment();
const factor = 5;
const time = [];
const minutes = now.minutes();
if (minutes !== 0 && minutes % factor) { // Check if there is a remainder
const remainder = minutes % factor; // Get remainder
now.add(factor - remainder, 'minutes'); // Update minutes value to nearest 5
}
for (let i = 0; i < 4; i++) {
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
now.add(5, 'minutes');
}
console.log(time);
Result:
now: 2019_10_11_09_19
["2019_10_10_21_20", "2019_10_10_21_25", "2019_10_10_21_30", "2019_10_10_21_35"]

Related

Sort and print number of occurences of random numbers

const randomNum = [];
for (let i = 0; i <= 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
then
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
My goal is to print out something along the line of
Number 1, 6, 12, 3, 9 occurred 1 times.
Number 2, 5, 7, 19, 17 occurred 2 times.
Number 15, 11 occurred 3 times.
And so on.
Any idea how i should go about this?
I was thinking of making a function, something along the line of
function numberOccurrence(arr, arrLength){
}
So i in the future could feed it ANY array with with x amount of numbers in it, but I'm unsure how to go forward.
I've tried multiple .includes, .indexOf, ifs and so forth, but i feel stuck, could anyone give me a push in the right direction?
I feel like having a loop which counts how many times 1 occurs, then saves that into an object like this
numObj = {
1: 2,
2: 1,
3: 4,
}
Where the object is built as soon as the function runs, and it builds it based on the arrLength parameter i feed the function in the beginning.
Anything is appreciated, thank you!
Update:
I manage to SOMETIMES print part of the answer right with this:
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
let numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
if (j === randomNum.length) {
printOut(`Number: ${numOccurr.join(', ')} occurrs ${i} times.`);
numOccurr = [];
}
}
}
}
}
if i check my array after "Number: 20 occurred 4 times" gets printed, i see that the answer is correct, problem is, sometimes it prints every number generated 1 time, then sometimes only those generated 2 times, and so on. And sometimes nothing gets printed
SOLVED:
This code worked for me
const randomNum = [];
for (let i = 0; i < 20; i += 1) {
randomNum.push(Math.floor(Math.random() * 20 + 1));
}
function getOccurrence(array, value) {
return array.filter((x) => x === value).length;
}
for (let i = 1; i <= randomNum.length; i += 1) {
const numOccurr = [];
for (let j = 1; j <= randomNum.length; j += 1) {
if (randomNum.includes(j)) {
if (getOccurrence(randomNum, j) === i) {
numOccurr.push(j);
}
}
}
if (numOccurr.length !== 0)
printOut(`Number: ${numOccurr.join(', ')} occurred ${i} times.`);
}

React Intl with relativeTime formatting

I'm working on a kind of dynamic timestamp for messages using Intl.
I want the timestamps to be dynamic in the way that it automatically transitions from ".. seconds ago" to "... minutes ago" to "... hours ago" to "today", after which it'll just return the date it's been posted. I know there's the <RelativeFormat> component, but I want to use the API instead.
The API has a method called intl.relativeFormat, but can't seem to figure out how to use it...
I'm a junior programmer so it's all still a bit new to me 😅😅
I appreciate your time :)
If you need more info, please let me know. I'll try to provide you with more.
Thanks!
Documentation for the RelativeFormat function can be found here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat.
The idea is that you create an instance of relative time format function, with some pre-defined settings that you want the output to follow. For example, you can set your relative time format function to return English strings in a shortened format.
const rtf = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtf.format(3, 'quarters'));
//expected output: "in 3 qtrs."
You also need to pass negative values in order to get labels intended for the past.
const rtf = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtf.format(-3, 'quarters'));
//expected output: "3 qtrs. ago"
The next part leverages an answer given by #fearofawhackplanet here on StackOverflow
//The 'timestamp' function parameter is your timestamp passed in milliseconds.
function timeDifference(timestamp, locale) {
const msPerMinute = 60 * 1000;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
const msPerMonth = msPerDay * 30;
const msPerYear = msPerDay * 365;
const current = Date.now();
const elapsed = current - timestamp;
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
if (elapsed < msPerMinute) {
return rtf.format(-Math.floor(elapsed/1000), 'seconds');
}
else if (elapsed < msPerHour) {
return rtf.format(-Math.floor(elapsed/msPerMinute), 'minutes');
}
else if (elapsed < msPerDay) {
return rtf.format(-Math.floor(elapsed/msPerHour), 'hours');
}
else {
return new Date(timestamp).toLocaleDateString(locale);
}
}
//
// code to test the above function
//
const fifteenSecondsAgo = new Date();
const tenMinutesAgo = new Date();
const twoHoursAgo = new Date();
fifteenSecondsAgo.setSeconds(fifteenSecondsAgo.getSeconds() - 15);
tenMinutesAgo.setMinutes(tenMinutesAgo.getMinutes() - 10);
twoHoursAgo.setHours(twoHoursAgo.getHours() - 2);
console.log(timeDifference(fifteenSecondsAgo.getTime(), 'en'));
console.log(timeDifference(fifteenSecondsAgo.getTime(), 'es'));
console.log(timeDifference(tenMinutesAgo.getTime(), 'en'));
console.log(timeDifference(tenMinutesAgo.getTime(), 'es'));
console.log(timeDifference(twoHoursAgo.getTime(), 'en'));
console.log(timeDifference(twoHoursAgo.getTime(), 'es'));
Here is a JSFiddle link to see the code running - https://jsfiddle.net/mhzya237/1/
Here is a similar idea, it also deals with future/present/past times.
function getRelativeTime(time) {
const now = new Date();
const diff = Math.abs(time - now);
const mark = (time - now) >> -1 || 1;
if (diff === 0) return new Intl.RelativeTimeFormat('en').format(0,"second");
const times = [
{ type: 'second', seconds: 1000 },
{ type: 'minute', seconds: 60 * 1000 },
{ type: 'hour', seconds: 60 * 60 * 1000 },
{ type: 'day', seconds: 24 * 60 * 60 * 1000 },
{ type: 'week', seconds: 7 * 24 * 60 * 60 * 1000 },
{ type: 'month', seconds: 30 * 24 * 60 * 60 * 1000 },
{ type: 'year', seconds: 12 * 30 * 24 * 60 * 60 * 1000 },
];
let params = [];
for (let t of times) {
const segment = Math.round(diff / t.seconds);
if (segment >= 0 && segment < 10) {
params = [(segment * mark) | 0, t.type];
break;
}
}
return new Intl.RelativeTimeFormat('en').format(...params);
}
const time = getRelativeTime(new Date(new Date().getTime() - 2 * 1000));
console.info('relative time is', time);
The function takes a time param, finds the seconds difference relative to now, uses the array map to calculate which type yields the closest match and uses it as a param for Intl.RelativeTimeFormat
You can improve getRelativeTime(time) function by either returning the params array and call Intl.RelativeTimeFormat from outside the function or also pass the locale (and options) to the function.
I'm sure there are smarter ways to get rid of the times array, perhaps by creating a wrapping closure but it will force you to "initialize" this utility function first

Limit react-day-picker range to x days

I want to limit the range length in react-day-picker to e.g. 10 days. How should this be done, is something availlable in the package already?
This is an example range selector: https://react-day-picker.js.org/examples/selected-range/
Could be easily implemented, I've just added some lines to the handleDayClick function:
Instead of this:
handleDayClick(day) {
const range = DateUtils.addDayToRange(day, this.state);
this.setState(range);
}
Implement this:
handleDayClick(day) {
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(Math.abs((day - this.state.from) / oneDay));
const range = DateUtils.addDayToRange(day, undefined);
if(diffDays <= 10){
const range = DateUtils.addDayToRange(day, this.state);
this.setState(range);
}
else {
this.setState(range);
}
}

Performance of array reverse in ActionScript 3

I have two code snippets . which one is better.
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
texts.reverse();
for(var index:int=0; index < texts.length; index++) {
trace(texts[index]);
}
Or
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
for( var index:int = texts.length; --index;) {
trace(texts[index]);
}
In former we have reverse operation and then print it and in latter we start from the length and start printing the array. The goal is to traverse the array from last.
I wrote a script which evaluates time elapsed between for loops. After running the application numerous of times, it appears that the 2nd for loop is fastest.
Averaging: 4.168000000000001 | 4.163000000000002 seconds respectively for 100 iterations of each for loop.
The script is as follows:
import flash.events.Event;
var _t:int = getTimer();
var dt:Number;
var started:Boolean = false;
var iteration:int = 0;
var timer1:Number = 0;
var timer2:Number = 0;
var numberOfIterations = 100;
var texts1:Array = new Array(1,2,3,4,5,6,7,8,9,10);
var texts2:Array = new Array(1,2,3,4,5,6,7,8,9,10);
texts2.reverse();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
addEventListener(Event.EXIT_FRAME, onExitFrame);
function onEnterFrame(e:Event):void {
var t:int = getTimer();
dt = (t - _t) * 0.001;
_t = t;
iteration++;
// small FLA load buffer
if(iteration == 50 && !started)
{
iteration = 0;
started = true;
}
}
function onExitFrame(e:Event):void {
if(started)
{
if(iteration < numberOfIterations)
{
for(var index:int=0; index < texts1.length; index++) {}
timer2 += dt;
trace("Time Elapsed Alg 2: " + (timer2));
}
else
{
for( var index:int = texts2.length; --index;) {}
timer1 += dt;
trace("Time Elapsed Alg 1: " + (timer1));
}
if(iteration == ((numberOfIterations*2)-1))
{
trace("________________________________________");
trace("FINAL: " + timer1 + " | " + timer2);
removeEventListener(Event.EXIT_FRAME, onExitFrame);
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
}
I am interested to see what others get using the following script, as it seems reliable on my PC as if I switch the for loop positions, the results still indicate that the fastest is:
var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
for( var index:int = texts.length; --index;) {
trace(texts[index]);
}
The first one doesn't trace the last item in the array ie 1
The second one does.
So I say the second is better.
I'm curious though - what's the correct way to code the first one so that it traces all the items in the array?

Angular_time filter

I want to make time filter which will show + if time is positive and - if time is negative (I have some calculations received from server), and showing only hours and minutes.
I did folowing, please comment on how this could be better
timeClock.filter('signedDuration', function () {
return function (timespan) {
if (timespan) {
var hoursInDay = 24;
var days = moment.duration(timespan).days();
var hours = moment.duration(timespan).hours();
var totalHours = (days * hoursInDay + hours);
totalHours = totalHours > 0 ? "+" + totalHours
: totalHours;
var minutes = moment.duration(timespan).minutes();
minutes = minutes < 0 ? Math.abs(minutes)
: minutes;
var output = '';
output += totalHours + 'h ';
output += minutes + 'm';
return output;
}
};
});

Resources