Loading...
More JavaScript Posts
//JavaScript program to swap two variables//take input from the userslet a = prompt('Enter the first variable: ');let b = prompt('Enter the second variable: ');// XOR operatora = a ^ bb = a ^ ba = a ^ bconsole.log(`The value of a after swapping: ${a}`);console.log(`The value of b after swapping: ${b}`);
router.post("/", async (req, res) => {const { email, password } = req.body;try {if (!email) return res.status(400).json({ msg: "An email is required" });if (!password)return res.status(400).json({ msg: "A password is required" });const user = await User.findOne({ email }).select("_id password");if (!user) return res.status(400).json({ msg: "Invalid credentials" });const match = await bcrypt.compare(password, user.password);if (!match) return res.status(400).json({ msg: "Invalid credentials" });const accessToken = genAccessToken({ id: user._id });const refreshToken = genRefreshToken({ id: user._id });res.cookie("token", refreshToken, {expires: new Date(Date.now() + 604800),httpOnly: true,});res.json({ accessToken });} catch (err) {console.log(err.message);res.status(500).json({ msg: "Error logging in user" });}});
class Timer{start(){this.startTime = Date.now();}stop(){const dt = Date.now() - this.startTime;console.log(dt);return dt;}getExecTime(fun, asynchronous){return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun);}getSyncExecTime(fun){this.start();fun();return this.stop();}async getAsyncExecTime(fun){this.start();await fun();return this.stop();}static average(fun, numTimes, asynchronous = false){const times = [];const promises = [];let timer = new Timer();if(asynchronous){for(let i = 0; i < numTimes; i++){timer.getAsyncExecTime(fun);}}else{for(let i = 0; i < numTimes; i++){timer.getSyncExecTime(fun);}}return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length);}static async timeAsync(fun, numTimes){if(numTimes <= 1) return new Timer().getAsyncExecTime(fun);const promises = [];let timer = new Timer(true);for(let i = 0; i < numTimes; i++){promises.push(fun().catch((e)=>{}));}try{await Promise.all(promises).catch((e)=>{});}catch(e){//do absolutely nothing}return timer.stop();}constructor(start = false){if(start) this.start();}}
// Time Complexity : O(N)// Space Complexity : O(1)var isMonotonic = function(nums) {let isMono = null;for(let i = 1; i < nums.length; i++) {if(isMono === null) {if(nums[i - 1] < nums[i]) isMono = 0;else if(nums[i - 1] > nums[i]) isMono = 1;continue;}if(nums[i - 1] < nums[i] && isMono !== 0) {return false;}else if(nums[i - 1] > nums[i] && isMono !== 1) {return false;}}return true;};let nums1 = [1,2,2,3]let nums2 = [6,5,4,4]let nums3 = [1,3,2]console.log(isMonotonic(nums1));console.log(isMonotonic(nums2));console.log(isMonotonic(nums3));
//Disclaimer: I do not condone mass web scraping of ESPN websites, and this is just theoretical code that hasn't been used.//Scrape player stats off of https://www.espn.com/nfl/team/roster/_/name/phi/philadelphia-eagles//Example player JS object/*{"shortName": "S. Opeta","name": "Sua Opeta","href": "http://www.espn.com/nfl/player/_/id/3121009/sua-opeta","uid": "s:20~l:28~a:3121009","guid": "dec19157-e984-f981-3724-498281328c97","id": "3121009","height": "6' 4\"","weight": "305 lbs","age": 27,"position": "G","jersey": "78","birthDate": "08/15/96","headshot": "https://a.espncdn.com/i/headshots/nfl/players/full/3121009.png","lastName": "Sua Opeta","experience": 4,"college": "Weber State"}*///The page needs to be focused, so you have to put this code in a bookmarklet and click the page before clicking it. Allegedly.navigator.clipboard.writeText(JSON.stringify(window["__espnfitt__"].page.content.roster.groups.flatMap((group)=>{return group.athletes.map((athlete)=>{//We can assume all football players are above 100 lbs and below 1000 lbs.athlete.weight = parseInt(athlete.weight.substring(0,3));if(athlete.experience == "R") athlete.experience = 0;else athlete.experience = parseInt(athlete.experience);//We can assume players are at least 1 foot, or under 10 feet tall.athlete.inches = 12 * parseInt(athlete.height.substring(0, 1)); //Add feet in inchesathlete.inches += parseInt(athlete.height.substring(2).replaceAll("\"", "").trim()); //Add remaining inchesconst monthDayYear = athlete.birthDate.split("/");athlete.birthMonth = parseInt(monthDayYear[0]);athlete.birthDay = parseInt(monthDayYear[1]);athlete.birthYear = parseInt(monthDayYear[2]);//The only really useful stuff we get from this is Height, weight, left handedness, age, position, and birthdayreturn athlete;});}), null, "\t")).then(null, ()=>{alert("That failed.")});//Changes all the team links on this page https://www.espn.com/nfl/stats/team to the team's roster for easier scraping$$("table > tbody > tr > td > div > div > a").forEach((elm)=>{elm.setAttribute("href", elm.getAttribute("href").replace("team/", "team/roster/"));});
if (process.env.NODE_ENV === "production") {app.use(express.static("client/build"));app.get("*", (req, res) => {res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));});}