diff --git a/README.md b/README.md index 888e422..871b750 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ 1. [Important Methods](#methods) ## Methods -> Most important javascript build in methods +> Hello Javascript - [1.1](#typeof) **typeof**: Returns the type. @@ -118,8 +118,30 @@ console.log(user); // TypeError: Cannot assign to read only property 'age' of ob ``` -- [1.5](#rename) **rename**: Rename multiple files extentions at once by a command (Just for Win). +- [1.7](#rename) **rename**: Rename multiple files extentions at once by a command (Just for Win). ```javascript Get-ChildItem *.css | Rename-Item -NewName { $_.name -Replace '\.css','.scss' } ``` + + +- [1.8](#majority) **majority**: Find Majority Element. + +```javascript +function majorityElement(arr) { + let count = 0, candidate = null; + + for (let num of arr) { + if (count === 0) candidate = num; + count += (num === candidate) ? 1 : -1; + } + + return candidate; +} + +// Time complexity: O(n) +// Space complexity: O(1) + +const arr = [3, 2, 3, 4, 3, 1, 6, 6, 7, 8, 6, 9, 6]; +console.log(majorityElement(arr)); // Output: 6 +``` diff --git a/js-coding-technique/fetchURLsWithDelay.js b/js-coding-technique/fetchURLsWithDelay.js new file mode 100644 index 0000000..afb3d89 --- /dev/null +++ b/js-coding-technique/fetchURLsWithDelay.js @@ -0,0 +1,31 @@ +function fetchURLsWithDelay(urls) { + let index = 0; + + function fetchNext() { + if (index < urls.length) { + fetch(urls[index]) + .then(response => { + if (!response.ok) { + throw new Error('Network response was not ok'); + } + return response.json(); + }) + .then(data => { + console.log('Data fetched:', data); + index++; + setTimeout(fetchNext, 1000); // 1000 milliseconds = 1 second + }) + .catch(error => { + console.error('Error fetching data:', error); + index++; + setTimeout(fetchNext, 1000); // Move to next URL even if there's an error + }); + } + } + + fetchNext(); +} + +// Example usage: +const urls = ['https://example.com/url1', 'https://example.com/url2']; +fetchURLsWithDelay(urls);