Javascript timestamp number is not unique - javascript

I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
I know the above returns the number of milliseconds.
But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
My question is Why is it not unique? and how do i get unique number from current date/time?

If you need uniqueness, use Math.random(), and not any of the Date() APIs.
Math.random returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date API with Math.random. For example:
var id = new Date().getTime() + Math.random();
In modern browsers, you can also use performance.now(). This API guarantees that every new call's return value is unique.

On Windows the resolution of the timer is about 10.5 ms. So you have chances of getting the same value even few milliseconds later. There are better timers of course, but AFAIK they are not available to JavaScript.

example.Even performance.now() sometimes don't give unique numbers. You have to make your own system to generate it. Something like make a counter and increase it by 1 each time when it is accessed.

Related

How to stop a function from executing more than x times per day?

In Google Sheets Script, how do I stop a function from executing more than x e.g. 5 times a day?
For instance, I have a trigger that executes a function every 20 minutes that sends an email based on a condition in the function, however I only want it to send this email a maximum of 5 times a day. How would I do this?
As other users recommended, you can store a value in the Project Properties, and use it to count how many times the script has been executed. I recommend you to use a condition to compare the new property with 5.
Remind to convert the property returned result type to Integer, as it is an
String by default, otherwise you won't be able to add 1 in each
execution.
As an example we can use the setProperty to modify the already saved value, for example:
var userProperties = PropertiesService.getUserProperties();
var newValue = +userProperties.getProperty('Execution_times') + 1;
userProperties.setProperty('Execution_times', newValue); // Updates stored value.

Uploading multiple images with timestamp as their name [duplicate]

I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
I know the above returns the number of milliseconds.
But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
My question is Why is it not unique? and how do i get unique number from current date/time?
If you need uniqueness, use Math.random(), and not any of the Date() APIs.
Math.random returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date API with Math.random. For example:
var id = new Date().getTime() + Math.random();
In modern browsers, you can also use performance.now(). This API guarantees that every new call's return value is unique.
On Windows the resolution of the timer is about 10.5 ms. So you have chances of getting the same value even few milliseconds later. There are better timers of course, but AFAIK they are not available to JavaScript.
example.Even performance.now() sometimes don't give unique numbers. You have to make your own system to generate it. Something like make a counter and increase it by 1 each time when it is accessed.

How can I set the Unix epoch of a moment js object?

I have a moment.js object whose Unix epoch value I'd like to change.
Normally I'd use myMoment = moment(someEpoch);, but because of design constraints I'm having to pass the object by reference, so I must mutate the value rather than replacing it altogether.
What is the neatest and (ideally) most performant way to do this in v2.15+?
Assuming m is a moment object, and t is the timestamp to set (in ms), probably the easiest way is:
m.add(t-m);
Or if you prefer to be more verbose:
m.add(t - m.valueOf(), 'ms');
Note that the default units are milliseconds when not specified and the input is numeric. If your input timestamp is in whole seconds, you'd have to multiply it by 1000 in either of the above formulas before subtracting the value of m.
However, if you're really after the most efficient code in terms of minimizing total operations performed internally, you could modify moment internals directly. Doing so is dangerous in that there's no guarantee the internals won't change between versions. Only the public API compatibility is guaranteed, following SemVer rules. So only do this if you are optimizing for perf and are willing to deal with potentially breaking changes in the future:
m._d.setTime(t + ((m._offset || 0) * 60000));
This is essentially an inversion of moment's valueOf function, and is probably what the implementation would look like if it were built in to moment.
Of course, if you are only working with moments in UTC mode, you can just do:
m._d.setTime(t);
One last thing, with regard to terminology, you can't actually set "the Unix epoch value", because the epoch is a fixed value. In this context, "epoch" means the timestamp that is zero, which is associated with 1970-01-01T00:00:00.000Z. It cannot be changed. You are simply using a "Unix Timestamp in milliseconds", or perhaps an "epoch-based timestamp". But it is a misnomer for your variable to be named someEpoch.
moment.js has a method to do that:
moment.unix(Number)
http://momentjs.com/docs/#/parsing/unix-timestamp/

new Date(epoch) returning invalid date inside Ember component

I have a date-filter component that I am using in my Ember application that only works on initial render, not on a page reload, or even if I save a file (which triggers the application to live update).
In the main template of my application, I render the date-filter like this passing it a unix timestamp
{{date-filter unixepoch=item.date}}
Then, in components/date-filter.js, I use a computed property called timeConverter to change the unix epoch into a time string formatted according to user's language of choice, and then in my templates/components/date-filter.hbs file I do {{timeConverter}} to display the results
timeConverter: function(){
//step 1: get the epoch I passed in to the component
var epoch = this.get('unixepoch');
//step 2: create a human readable date string such as `Jun 29, 2015, 12:36PM`
var datestring = new Date(epoch)
//do language formatting --code omitted as the problem is with step2
}
It is step 2 that fails (returning invalid date) if I refresh the page or even save the file. It always returns the proper date string the first time this component is called. Even if I do new Date(epoch) in the parent component, and try to pass the result in to this component (to do foreign language formatting), I'm having the same problem.
Question: how can I figure out what's happening inside new Date(epoch), or whether it's an issue related to the component?
I suspect your epoch value is a string (of all digits). If so, then
var datestring = new Date(+epoch);
// Note ------------------^
...will fix it by converting it to a number (+ is just one way to do it, this answer lists your options and their pros/cons). Note that JavaScript uses the newer "milliseconds since The Epoch" rather than the older (original) "seconds since The Epoch." So if doing this starts giving you dates, but they're much further back in time than you were expecting, you might want epoch * 1000 to convert seconds to milliseconds.
If it's a string that isn't all digits, it's not an epoch value at all. The only string value that the specification requires new Date to understand is the one described in the spec here (although all major JavaScript engines also understand the undocumented format using / [not -] in U.S. date order [regardless of locale]: mm/dd/yyyy — don't use it, use the standard one).

Dynamic Frequency Map from MongoDB Keys

I'm using MiniMongo through Meteor, and I'm trying to create a frequency table based off of a dynamic set of queries.
I have two main fields, localHour and localDay. I expect many overlaps, and I'd like to determine where the most overlaps occur. My current method of doing this is so.
if(TempStats.findOne({
localHour: hours,
localDay: day
})){//checks if there is already some entry on the same day/hour
TempStats.update({//if so, we just increment frequency
localHour: hours,
localDay: day
},{
$inc: {freq: 1}
})
} else {//if nothing exists yet, we put in a new entry
TempStats.insert({
localHour: hours,
localDay: day,
freq: 1
});
}
Essentially, this code runs every time I have new data I want to insert. It works fine at the moment, in that, after all data is inserted, I can sort by frequency to find what set of hours & days occurs the most often (TempStats.find({}, {sort: {freq: -1}}).fetch()).
However, I'm looking more for a way to search by frequency for any key. For instance, searching for the day which everything occurs on the most often as opposed to both the date and hour. With my current way of doing this, I would need to have multiple databases and different methods of inserting for each, which is a bit ridiculous. Is there a Mongo (specifically MiniMongo) solution to do frequency maps based on keys?
Thanks!
It looks like miniMongo does not in fact support aggregation, which makes this kind of operation difficult. One way to go about it would be aggregating yourself at the end of each day and inserting that aggregate record into your db (without the hour field or with it set to something like -1). Conversely as wastefully you could also update that record at the time of each insert. This would allow you to use the same collection for both and is fairly common in other dbs.
Also you should consider #nickmilon's first suggestion since the use of an upsert statement with the $inc operator would reduce your example to a single operation per data point.
a small note on your code: the part that comes as an else statement is not really required your update will do the complete job if you combine it with the option upsert=true it will insert a new document and $inc will set the freq field to 1 as desired see: here and here
for alternative ways to count your frequencies: assuming you store the date as a datetime object I would suggest to use an aggregation (I am not sure if they added support for aggregation yet in minimongo) but there are solutions then with aggregation you can use datetime operators as
$hour, $week, etc for filtering and $count to count the frequencies without you having to keep counts in the database.
This is basically a simple map-reduce problem.
First, don't separate the derived data into 2 fields. This violates DB best practices. If the data comes to you this way, use it to create a Date object. I assume you have a bunch of collections that are being subscribed to and then you aggregate all those into this temporary local collection. This is the mapping of the map-reduce pattern. At this point, since your query in unknown, it's a waste of CPU (even though it's your client) to aggregate. Map first, reduce second. What you should have is a collection full of datetimes. call it TempMapCollection if you wish. Now, use a forEach() and pass in your reduce function (by day, by hour, etc).
You can reduce into another local collection, or into a javascript object. I like using collections, but if the objects are complex, you'll get EJSON errors all up in there. Since your objects are nothing more than a datetime, let's use collections.
so you've got something like:
TempMapCollection.find().forEach(function(doc) {
var date = doc.dateTime.getDate();
TempReduceCollection.upsert({timequery: hours}, {$inc: {freq: 1}});
})
Now query your reduce collection. This has the added benefit that you won't have to re-map if you want to do 2 unique queries.

Categories

Resources