Skip to content

Instantly share code, notes, and snippets.

@krypton225
Last active January 3, 2023 17:26
Show Gist options
  • Save krypton225/dc9f543fe13dddc00d1be48e3ce3f6c9 to your computer and use it in GitHub Desktop.
Save krypton225/dc9f543fe13dddc00d1be48e3ce3f6c9 to your computer and use it in GitHub Desktop.
Generating IDs in array of objects.
/*
* This is just a module for generating IDs when you want mapping through array of objects (Useful in React JS).
* Learn about generator functions here: https://javascript.info/generators
* This code is made by using (Reavelling Design Pattern).
* Learn about this pattern here (Arabic explain) : shorturl.at/jkUW4
*/
/*
* File and name it: generate-id.js (feel free to name it as you want).
* Best practice to put this file in folder and name it: utils.
*/
const generateID = (function () {
/**
* @returns {number}
*/
function* getNumberID() {
let count = 1;
while (true) {
yield count++;
}
}
/**
* @param {Array} sourceArr=[] - array to check if it has objects or not.
*/
function isArrayNotEmpty(sourceArr = []) {
return sourceArr.length !== 0
}
/**
* @param {Array} dataArr=[] - array has objects and insert IDs into each one.
*/
function insertIDIntoData(dataArr = []) {
if (isArrayNotEmpty(dataArr)) {
const counter = getNumberID();
dataArr.forEach((row) => {
// Check that if each element in the array is type of object or not.
if (typeof row === "object") {
// Check if each object dose not have 'id' property and if not, then add 'id' property to this object.
if (!row.hasOwnProperty("id")) {
// row.id = counter.next().value; => you can use this instead of the coming.
// But the coming is the best to prevent any modifications in ID of each item in array (recommended).
Object.defineProperty(row, "id", {
value: counter.next().value,
writable: false,
enumerable: true
});
}
} else {
throw new Error(`Array ${dataArr.name} must contain only object.`);
}
});
} else {
throw new Error("Array must not be empty of objects.");
}
}
return {
insert: insertIDIntoData
}
})();
export default generateID.insert;
/* ================================================================= */
/* This is a file which contain array of object you want mapping through it */
/* Don't forget to import your module at the top of the file. */
import generateIDs from "../utils/generate-id.js";
/* Example */
const products = [
{ productName: "product 1", productPrice: "220" },
{ productName: "product 2", productPrice: "400" },
{ productName: "product 3", productPrice: "1000" },
{ productName: "product 4", productPrice: "80" },
{ productName: "product 5", productPrice: "100" },
];
/*
* This is IIFE which is called by itself.
* You can use arrow function to run the generator as you see.
*/
(() => generateIDs(products))();
/* You can see the IDs in each products by logging the products array. */
console.log(products);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment