Need to Auto generate key in Alphanumeric - javascript
I have to generate value with Alphanumeric. Here I've mentioned my function.
* Doubt in this function there is a key called category_no I have increment this key by Auto.
Expected Format: min value: C0001,C0002,C0003,,,,max value:C9999.
// Inserting New Category
async function postCategory() {
for (i = 0; i < categoryJson.length; i++) {
categoryDefault = {};
categoryDefault['category_no'] =
categoryDefault['category_overview'] = "No overview"
categoryDefault['category_description'] = "No description"
categoryDefault['category_created_date'] = new Date()
categoryDefault['category_modified_date'] = new Date()
const { error } = await
CategoryModel.validateNewCategory(categoryDefault)
let mongodb = await MongoDB.connect("ecomm_prod_db_category");
let result = await mongodb.insertOne(categoryDefault);
};
};
You can create a function as following to generate catagory_no,
Use String.prototype.padStart to keep the length of string 5 with 0 appended.
For counter use the unnamed self-invoking function passing the count as closure.
let catagory = (() => {
count = 1;
return () => {
if(count < 9999) {
return `C${(count++).toString().padStart(4, '0')}`
} throw('Max Limit Reached')
}
})();
console.log(catagory())
console.log(catagory())
console.log(catagory())
Related
Javascript find the most repetitive character occurrence from the string
Let's say we have this string: BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF As you can see, here B is occurring 4 times at first but B is also present before DDDD. Similarly, A is occurring 4 times at the beginning and later 6 times. I want the expected output if I am searching B it should 4 times as the max occurrence B is 4. However if I am searching A then it should return 6 because the most occurrence for A is 6. Here is my code I tried: function checkRepeatativeString(str) { let hashMap = {}; let seen = new Set(); let counter = 1; let maxValue = 1; let isPreviousValueSame = false; let isNextValueSame = true; for (let i = 0; i < str.length; i++) { /** * is previous value same */ if (str[i] == str[i-1]) { isPreviousValueSame = true; } /** * is next value same */ if (str[i] == str[i+1]) { isNextValueSame = true; } if (seen.has(str[i]) && isPreviousValueSame) { hashMap[str[i]][0]++; hashMap[str[i]][1]++; isPreviousValueSame = false; } else if(seen.has(str[i]) && !isNextValueSame) { maxValue = Math.max(hashMap[str[i]][1], maxValue); counter = 0; hashMap[str[i]] = [counter, maxValue]; } else { maxValue = Math.max(maxValue, counter); seen.add(str[i]); hashMap[str[i]] = [counter, maxValue]; isPreviousValueSame = false; } } return hashMap; } let str = "BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF"; console.log(checkRepeatativeString(str)); This code is working but if you look for B, I am getting stuck at the beginning of value. My program returns out for B: B: [ 1, 1 ] ^ ^ Inside array, 1 is a counter which scans the string and second 1 in array is a max value which should return the output. However my program is returning 1 for B. I am expecting 4 as max value. Help would be appreciated~
Quick and dirty. function maxConsecutiveCharacters(check, haystack) { if(check.length !== 1) return false; let result = 0; let buffer = 0; for(let i = 0; i < haystack.length; i++) { if(haystack[i] === check) { buffer++; } else { if(buffer > result) { result = buffer; } buffer = 0; } if(buffer > result) { result = buffer; } } return result; }
That looks overly complicated. Consider approaching the problem from a different angle - first split up the string into segments of repeating characters, and group them into an object based on the length of the longest substring for a given character. const checkRepeatativeString = (str) => { const longestCounts = {}; for (const consecutive of (str.match(/(.)\1*/g) || [])) { const char = consecutive[0]; longestCounts[char] = Math.max( longestCounts[char] || 0, // Use the existing value in the object if it exists and is higher consecutive.length // Otherwise, use the length of the string iterated over ); } return longestCounts; }; let str = "BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF"; console.log(checkRepeatativeString(str)); Simpler code often means less surface area for bugs.
Compare an array with itself for duplicate and store in new array
I have a question, how do I compare values in an array with themselves without the value to be compared being shown as true? As an example, if the value EUW1_6011808396 occurs again, it should be stored in the array matchingMatches. The Values of the Array are: [EUW1_6011808396, EUW1_6011824351, EUW1_6011720277, EUW1_6010413995, EUW1_6010218048, EUW1_6010184913, EUW1_6010131700, EUW1_6009739853, EUW1_6008825456, EUW1_6008833322, EUW1_6008409245, EUW1_6008369887, EUW1_6008355242, EUW1_6007567238, EUW1_6007269146, EUW1_6007226284, EUW1_6007192332, EUW1_6005571988, EUW1_6005438941, EUW1_6005495312, EUW1_6013263286, EUW1_6013193252, EUW1_6012475324, EUW1_6012411610, EUW1_6012315128, EUW1_6012011561, EUW1_6011110477, EUW1_6011026046, EUW1_6009739853, EUW1_6006439870, EUW1_6006434580, EUW1_6005238786, EUW1_6005191249, EUW1_6005026992, EUW1_6005015187, EUW1_6004958241, EUW1_6003811368, EUW1_6002847479, EUW1_6002164371, EUW1_6002148723, EUW1_6015524685, EUW1_6015387328, EUW1_6015402003, EUW1_6014779337, EUW1_6014724668, EUW1_6014701498, EUW1_6014655368, EUW1_6014580839, EUW1_6014429620, EUW1_6014475971, EUW1_6014473252, EUW1_6013334881, EUW1_6013322375, EUW1_6012669749, EUW1_6012635347, EUW1_6012583396, EUW1_6010971941, EUW1_6006896961, EUW1_6006881165, EUW1_6006518887, EUW1_6015745842, EUW1_6015589872, EUW1_6014068520, EUW1_6014044304, EUW1_6007955310, EUW1_6003705297, EUW1_6003569783, EUW1_6002003834, EUW1_6000787500, EUW1_5994465297, EUW1_5993391050, EUW1_5992233473, EUW1_5992169601, EUW1_5984062877, EUW1_5984034743, EUW1_5983855739, EUW1_5983880569, EUW1_5983766086, EUW1_5982931745, EUW1_5982372929, EUW1_6005238786, EUW1_6005191249, EUW1_6005026992, EUW1_6005015187, EUW1_6004958241, EUW1_6002164371, EUW1_6002148723, EUW1_6002057259, EUW1_6002053660, EUW1_6002009239, EUW1_6002003834, EUW1_6001939719, EUW1_6001867883, EUW1_6001022392, EUW1_6000887143, EUW1_6000892356, EUW1_6000787500, EUW1_6000820954, EUW1_5996485374, EUW1_5994559073, EUW1_6010083174, EUW1_6010017420, EUW1_6006898776, EUW1_6006838293, EUW1_6005225782, EUW1_6005135031, EUW1_6003899867, EUW1_6003883079, EUW1_6003786523, EUW1_6002164371, EUW1_6002148723, EUW1_6002057259, EUW1_6002053660, EUW1_6002009239, EUW1_6001022392, EUW1_6000887143, EUW1_6000892356, EUW1_6000787500, EUW1_5999368247, EUW1_5999295110, EUW1_5989231240, EUW1_5989055249, EUW1_5987149834, EUW1_5978125118, EUW1_5969701977, EUW1_5969187233, EUW1_5956294382, EUW1_5955846040, EUW1_5949708234, EUW1_5934525960, EUW1_5916275391, EUW1_5916168691, EUW1_5916132470, EUW1_5907690529, EUW1_5897979620, EUW1_5897921186, EUW1_5896786548, EUW1_5880625543, EUW1_5880541891, EUW1_5878457213, EUW1_6015589872, EUW1_5969852994, EUW1_5969788713, EUW1_5940681289, EUW1_5940556247, EUW1_5937866203, EUW1_5937892773, EUW1_5937768916, EUW1_5937765393, EUW1_5934600651, EUW1_5934512860, EUW1_5934339533, EUW1_5932238516, EUW1_5932166008, EUW1_5932211862, EUW1_5929934534, EUW1_5930153889, EUW1_5931242804, EUW1_5919621815, EUW1_5918236611] The function which is used for getting the Id for the API call. /** * Getting the Team Members and their IDs * * #param {info_id|String} * #return Team Members IDs * #customfunction */ function getTeamMembersIDs(info_id) { try { startup(); var teamMembers = getTeamMembersSheet(); var riotIds = []; for (var counter = 0; counter != teamMembers.length; counter = counter + 1) { switch (info_id){ case "puuid": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var puuid = data["puuid"]; riotIds.push(puuid); break; case "id": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var id = data["id"]; riotIDs.push(id); break; case "accountId": var data = buildURL("https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/"+teamMembers[counter]+"?api_key="+apiKey); var accountId = data["accountId"]; riotIds.push(accountId); break; } } return riotIds } catch (err) { Logger.log('Failed with error %s', err.message); } } This Function is Used for Getting the Matches that got played per Team Member. /** * Getting the Data from the Api which matches got played * * #return the matches played * #customfunction */ function getMatchesPlayed() { try{ startup(); var puuids = getTeamMembersIDs("puuid"); var games = []; for (var counter = 0; counter != puuids.length; counter = counter + 1) { var data = buildURL("https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/"+puuids[counter]+"/ids?start=0&count=20&api_key="+apiKey) for(var counter2 = 0; counter2 != data.length; counter2 = counter2 + 1){ games.push(data[counter2]) } } return games }catch (err) { Logger.log('Failed with error %s', err.message); } } The function which should return the Matching Matches in the Array gets from the getMatchesPlayed function. /** * Checking the games for matches * * #return the matches which match * #customfunction */ function getMatchingMatches() { try{ var games = getMatchesPlayed(); var matchingMatches = []; Logger.log(games) const gettingGames = games.map(element => element) for (var counter = 0; counter != games.length; counter = counter + 1){ Logger.log(gettingGames[counter]) } }catch (err) { Logger.log('Failed with error %s', err.message); } }
As I understand, you need to get duplicate ids. Use the Set data structure for comparing the array values. // assume this should return an array [EUW1_6011808396, EUW1_6011824351] var games = getMatchesPlayed(); // var matched_games = [] // Initialise set data structure. var set = = new Set(); //Iterate over the games. Runtime complexity O(n) games.forEach((element) => { //the case when set does not contain the id we should add it to `set` if(!set.has(element)){ // O(1) set.add(element); // O(1) continue; } // if the set already contains the id, we should add it to the matching games array. matched_games.push(element); }) I hope this will help.
welcome to Stackoverflow! You have a lot of ways to store duplicate values In a new array, and this is one. // get duplicartes and store them in a array function getDuplicates(array) { let sorted = array.sort(); for (let i = 0; i < sorted.length - 1; i++) { if (sorted[i + 1] == sorted[i]) { duplicates.push(sorted[i]); } } }
Another way to get non-unique values const euws = ['EUW1_6011808396','EUW1_6011824351','EUW1_6011720277','EUW1_6010413995','EUW1_6010218048','EUW1_6010184913','EUW1_6010131700','EUW1_6009739853','EUW1_6008825456','EUW1_6008833322','EUW1_6008409245','EUW1_6008369887','EUW1_6008355242','EUW1_6007567238','EUW1_6007269146','EUW1_6007226284','EUW1_6007192332','EUW1_6005571988','EUW1_6005438941','EUW1_6005495312','EUW1_6013263286','EUW1_6013193252','EUW1_6012475324','EUW1_6012411610','EUW1_6012315128','EUW1_6012011561','EUW1_6011110477','EUW1_6011026046','EUW1_6009739853','EUW1_6006439870','EUW1_6006434580','EUW1_6005238786','EUW1_6005191249','EUW1_6005026992','EUW1_6005015187','EUW1_6004958241','EUW1_6003811368','EUW1_6002847479','EUW1_6002164371','EUW1_6002148723','EUW1_6015524685','EUW1_6015387328','EUW1_6015402003','EUW1_6014779337','EUW1_6014724668','EUW1_6014701498','EUW1_6014655368','EUW1_6014580839','EUW1_6014429620','EUW1_6014475971','EUW1_6014473252','EUW1_6013334881','EUW1_6013322375','EUW1_6012669749','EUW1_6012635347','EUW1_6012583396','EUW1_6010971941','EUW1_6006896961','EUW1_6006881165','EUW1_6006518887','EUW1_6015745842','EUW1_6015589872','EUW1_6014068520','EUW1_6014044304','EUW1_6007955310','EUW1_6003705297','EUW1_6003569783','EUW1_6002003834','EUW1_6000787500','EUW1_5994465297','EUW1_5993391050','EUW1_5992233473','EUW1_5992169601','EUW1_5984062877','EUW1_5984034743','EUW1_5983855739','EUW1_5983880569','EUW1_5983766086','EUW1_5982931745','EUW1_5982372929','EUW1_6005238786','EUW1_6005191249','EUW1_6005026992','EUW1_6005015187','EUW1_6004958241','EUW1_6002164371','EUW1_6002148723','EUW1_6002057259','EUW1_6002053660','EUW1_6002009239','EUW1_6002003834','EUW1_6001939719','EUW1_6001867883','EUW1_6001022392','EUW1_6000887143','EUW1_6000892356','EUW1_6000787500','EUW1_6000820954','EUW1_5996485374','EUW1_5994559073','EUW1_6010083174','EUW1_6010017420','EUW1_6006898776','EUW1_6006838293','EUW1_6005225782','EUW1_6005135031','EUW1_6003899867','EUW1_6003883079','EUW1_6003786523','EUW1_6002164371','EUW1_6002148723','EUW1_6002057259','EUW1_6002053660','EUW1_6002009239','EUW1_6001022392','EUW1_6000887143','EUW1_6000892356','EUW1_6000787500','EUW1_5999368247','EUW1_5999295110','EUW1_5989231240','EUW1_5989055249','EUW1_5987149834','EUW1_5978125118','EUW1_5969701977','EUW1_5969187233','EUW1_5956294382','EUW1_5955846040','EUW1_5949708234','EUW1_5934525960','EUW1_5916275391','EUW1_5916168691','EUW1_5916132470','EUW1_5907690529','EUW1_5897979620','EUW1_5897921186','EUW1_5896786548','EUW1_5880625543','EUW1_5880541891','EUW1_5878457213','EUW1_6015589872','EUW1_5969852994','EUW1_5969788713','EUW1_5940681289','EUW1_5940556247','EUW1_5937866203','EUW1_5937892773','EUW1_5937768916','EUW1_5937765393','EUW1_5934600651','EUW1_5934512860','EUW1_5934339533','EUW1_5932238516','EUW1_5932166008','EUW1_5932211862','EUW1_5929934534','EUW1_5930153889','EUW1_5931242804','EUW1_5919621815','EUW1_5918236611']; const nonUnique = euws.reduce((r, v, i, a) => { if (!r.includes(v) && a.indexOf(v) !== i) r.push(v); return r; }, []); console.log(nonUnique) .as-console-wrapper { max-height: 100% !important; top: 0 }
Using data i get from request function in node.JS again until a condition is met
I want to access shopify api using Node.js with request method. I get first 50 items but i need to send the last id of the products i get as a response so it can loop through all the products until we don't have another id (i check that if the last array is not 50 in length.) So when i get the response of lastID i want to feed that again to the same function until the Parraylength is not 50 or not 0. Thing is request works asynchronously and i don't know how to feed the same function with the result lastID in node.js. Here is my code let importedData = JSON.parse(body); //for ( const product in importedData.products ){ // console.log(`${importedData.products[product].id}`); //} lastID = importedData.products[importedData.products.length-1].id; let lastIDD = lastID; console.log(`This is ${lastID}`); importedData ? console.log('true') : console.log('false'); let Prarraylength = importedData.products.length; console.log(Prarraylength); //console.log(JSON.stringify(req.headers)); return lastIDD; });```
You can use a for loop and await to control the flow of your script in this case. I'd suggest using the request-native-promise module to get items, since it has a promise based interface, but you could use node-fetch or axios (or any other http client) too. In this case, to show you the logic, I've created a mock rp which normally you'd create as follows: const rp = require("request-promise-native"); You can see we're looping through the items, 50 at a time. We're passing the last id as a url parameter to the next rp call. Now this is obviously going to be different in reality, but I believe you can easily change the logic as you require. const totalItems = 155; const itemsPerCall = 50; // Mock items array... const items = Array.from({ length: totalItems}, (v,n) => { return { id: n+1, name: `item #${n+1}` } }); // Mock of request-promise (to show logic..) // Replace with const rp = require("request-promise-native"); const rp = function(url) { let itemPointer = parseInt(url.split("/").slice(-1)[0]); return new Promise((resolve, reject) => { setTimeout(() => { let slice = items.slice(itemPointer, itemPointer + itemsPerCall); itemPointer += itemsPerCall; resolve( { products: slice }); }, 500); }) } async function getMultipleRequests() { let callIndex = 0; let lastID = 0; const MAX_CALLS = 20; const EXPECTED_ARRAY_LENGTH = 50; for(let callCount = 1; callCount < MAX_CALLS; callCount++) { // Replace with the actual url.. let url = "/products/" + lastID; let importedData = await rp(url); lastID = importedData.products[importedData.products.length - 1].id; console.log("Call #: " + ++callIndex + ", Item count: " + importedData.products.length + ", lastID: " + lastID); if (importedData.products.length < EXPECTED_ARRAY_LENGTH) { console.log("Reached the end of products...exiting loop..."); break; } } } getMultipleRequests();
I need my array to return and array back to another variable while also including its previous array members, no idea how to go about it
This is the test code that it's supposed to pass function makeArray() { const array = []; const t = 10; for (let i = 0; i < t; i++) { array.push("I am a strange loop."); } return [array, t]; } describe('loops', () => { jsdom({ src: fs.readFileSync(path.resolve(__dirname, '..', 'loops.js'), 'utf-8'), }); describe('forLoop(array)', () => { it('adds `"I am ${i} strange loop${i === 0 ? \'\' : \'s\'}."` to an array 25 times', () => { const [array, t] = makeArray(); const strangeArray = forLoop(array); const testArray = strangeArray.slice(array.length); const first = "I am 1 strange loop."; const rest = "I am 24 strange loops."; expect(strangeArray[11]).to.equal(first); expect(strangeArray[34]).to.equal(rest); expect(strangeArray.length).to.equal(t + 25); }); }); }); this is my code to return the function to strangeArray what I am thinking is that 35 is the total number of members in the array and as the test pass requires me to have 'expect(strangeArray[11]).to.equal(first)' 11th value to be equal to my function return as "I am 1 strange loop." function forLoop(array) { for (let i = 0; i < 35; i++) { if (array[i] === "I am a strange loop.") { return; } else { array.push("I am ${i} strange loops."); } } return [array,i]; }
Not sure what you mean exactly but I guess you just want the test to pass? The problem is that the first loop has 'loop' as singular and your indexes don't work either since they would start at 11. That's why your code doesn't work. You can just push to the original array. function forLoop(array){ for(let i = 0; i < 25; i++){ array.push(`I am ${i} strange loop${i > 1 ? '' : 's'}.`) } return array }
Undefined value from looping through json
In typescript/javascript I'm trying to fetch 'statute' from data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} So I assign data.law to a variable. But, I'm getting typeerror cannot read property 'law' of undefined? If I console log 'data.law' at line 11 or result[0] at the line 18 I get the correct value... sectionsSuccess(res: Response) { this.allSections = []; this.sections = []; this.loadingSections = false; try { let jsonRes = res.json(); this.jsonResLength = jsonRes.length; for (var a = 0; a < this.jsonResLength; a++) { let js = jsonRes[a]; js.bookmarked = this.server.isInBookmark(js); this.allSections.push(js); if (a < 15) { this.sections[a] = this.allSections[a]; } } } catch (e) { alert("Exception: " + e.message); } for (var i = 0; i < this.allSections.length; i++) { this.allSections[i] = this.convertLocationDataToStatutes(this.allSections[i]); } // complete code added above for (var i = 0; i < this.sections.length; i++) { this.sections[i] = this.convertLocationDataToStatutes(this.sections[i]); } } convertLocationDataToStatutes(data: any): any { var self = this; var chapterandsection = data.law; //line 11 var values = chapterandsection.split('-'); var chapter = values[0]; var section = values[1]; (self.server).getSection(chapter, section) .map(response => response.json()).subscribe(result => { return result[0]; // line 18 }); }
Your convertLocationDataToStatutes never returns anything, but you're using its return value. The result of calling a function with no return value is undefined. So the loop fills this.sections with a bunch of undefineds. That means the next time sectionsSuccess gets called, it will see undefined in this.sections[x], and accessing data.law on it will cause the error. So the problem will present the second time sectionsSuccess is called; your logging of data.law where you saw the value presumably was the first call to it. The only return in convertLocationDataToStatutes is the one inside the subscribe callback. Presumably you meant to return something from convertLocationDataToStatutes itself.