Last active
July 10, 2016 00:34
-
-
Save Akamaozu/e00b10ef1322a7fb26c7c7be811f7b11 to your computer and use it in GitHub Desktop.
Generate Unique IDs, Release It When Consumed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function id_generator(){ | |
var store = {}; | |
function release_id( id ){ | |
delete store[ id ]; | |
} | |
function generate_unique_id(){ | |
var candidate_id = generate_id(); | |
if( !is_unique_id( candidate_id ) ){ | |
candidate_id = generate_unique_id(); | |
} | |
store[ candidate_id ] = true; | |
return candidate_id; | |
} | |
function is_unique_id( id ){ | |
return !store.hasOwnProperty( id ); | |
} | |
function generate_id(){ | |
return require('uuid').v4(); | |
} | |
return { | |
create: generate_unique_id, | |
release: release_id | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var job_ids = id_generator(); | |
// get new job id | |
job_id = job_ids.create(); | |
// do job | |
// - other ids get assigned to other jobs | |
// - but each job id is guaranteed to be unique | |
// on job completion | |
job_ids.release( job_id ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment