Really weird JS pattern for generating sequential IDs with modules:

components/my-module.js

let id = 0; export function generateThing(attrs) { return Object.assign({ id: ++, }, attrs); }

index.js

import { generateThing } from './components/my-module'; generateThing().id; // 1 generateThing().id; // 2 generateThing().id; // 3

It works because the module itself keeps its own state. Modules are only ever imported once, and re-importing them reuses the existing module.

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.