2

I would like to generate a unique id with javascript without exceeding an integer type.

I see it: create unique id with javascript

With the following solution: (new Date()).getTime() but out of the range of an integer.

Thanks for your suggestion.

6
  • 2
    What's your "range of integer" here? Commented Apr 23, 2013 at 18:39
  • 2
    (pretty much any expression) | 0 will return a value from 0 to 2^32-1. (expr) >>> 1 will half that range. Commented Apr 23, 2013 at 18:44
  • My range for int is: -2147483648 until 2147483647. If possible I prefer using negative values so from -2147483648 to 0. Commented Apr 23, 2013 at 18:47
  • Have you read the other answers on that linked post? A running index is very simple, and you can define its range very easily. Commented Apr 23, 2013 at 18:50
  • 1
    @Salman: you are right. I mean an integer in a more general sense. To be more precise I use c-sharp integers. Commented Apr 23, 2013 at 19:00

2 Answers 2

4

Depends on what size integer you want. Here is a fiddle that shows a couple of ways to do it: http://jsfiddle.net/leemeador/C6YGa/

The idea is to do something like this for a 32 bit integer:

var i = new Date().getTime();
i = i & 0xffffffff;
Sign up to request clarification or add additional context in comments.

2 Comments

Your solution is very interesting. One question: by using this 0xffff what is the range? Thanks.
Each 'F' is 4 bits. FFFF is 16 bits. FFFFFFFF is 32 bits.
0

Another way to generate unique key (id) with new ES6 Syntax, by returning a Number representing the milliseconds elapsed since the UNIX epoch:

export const generateRandomKey = () => Date.now();

You can write it in separate file and export. than import to your file using es6 syntax.

import {generateRandomKey} from './the/file/path.js';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.