Loading...
More JavaScript Posts
function copyString(text){async function navigatorClipboardCopy(text){if(document.location.protocol != "https:"){return false;}return new Promise((resolve, reject)=>{navigator.clipboard.writeText(text).then(()=>{resolve(true);}, ()=>{resolve(false);});});}function domCopy(text){if(!(document.execCommand)){console.warn("They finally deprecated document.execCommand!");}const input = document.createElement('textarea');input.value = text;document.body.appendChild(input);input.select();const success = document.execCommand('copy');document.body.removeChild(input);return success;}function promptCopy(){prompt("Copy failed. Might have ... somewhere. Check console.", text);console.log(text);}function done(){alert("Copied to clipboard");}navigatorClipboardCopy(text).catch(()=>{return false;}).then((success)=>{if(success){done();}else{if(domCopy(text)){done();}else{promptCopy();}}});}
function formatDate(date) {return date.toLocaleDateString();}function Comment(props) {return (<div className="Comment"><div className="UserInfo"><imgclassName="Avatar"src={props.author.avatarUrl}alt={props.author.name}/><div className="UserInfo-name">{props.author.name}</div></div><div className="Comment-text">{props.text}</div><div className="Comment-date">{formatDate(props.date)}</div></div>);}const comment = {date: new Date(),text: 'I hope you enjoy learning React!',author: {name: 'Hello Kitty',avatarUrl: 'https://placekitten.com/g/64/64',},};ReactDOM.render(<Commentdate={comment.date}text={comment.text}author={comment.author}/>,document.getElementById('root'));
const levenshteinDistance = (s, t) => {if (!s.length) return t.length;if (!t.length) return s.length;const arr = [];for (let i = 0; i <= t.length; i++) {arr[i] = [i];for (let j = 1; j <= s.length; j++) {arr[i][j] =i === 0? j: Math.min(arr[i - 1][j] + 1,arr[i][j - 1] + 1,arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1));}}return arr[t.length][s.length];};levenshteinDistance('duck', 'dark'); // 2
const compactObject = val => {const data = Array.isArray(val) ? val.filter(Boolean) : val;return Object.keys(data).reduce((acc, key) => {const value = data[key];if (Boolean(value))acc[key] = typeof value === 'object' ? compactObject(value) : value;return acc;},Array.isArray(val) ? [] : {});};const obj = {a: null,b: false,c: true,d: 0,e: 1,f: '',g: 'a',h: [null, false, '', true, 1, 'a'],i: { j: 0, k: false, l: 'a' }};compactObject(obj);// { c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }
//Allegedly never tested on the twitter websitefunction scrapeScreen(){let articles = Array.from(document.getElementsByTagName("article"));let results = [];for(let tweet of articles){const isAnAd = Array.from(tweet.querySelectorAll("span")).map((e)=>e.textContent).includes("Ad");if(isAnAd){//console.log(tweet, "is an ad. Skipping...");continue;}const userName = tweet.querySelector("[data-testid='User-Name'] > div:nth-child(2) > div > div")?.textContent;const tweetContent = tweet.querySelector("[data-testid='tweetText']")?.textContent;const timeStamp = tweet.querySelector("time")?.getAttribute("datetime");const tweetLink = tweet.querySelector("time")?.parentElement?.getAttribute("href");if((!userName) || (!tweetContent)) continue;results.push({username: userName,tweetText: tweetContent,timeStamp: timeStamp,tweetLink: tweetLink});}return results;}let scraped = scrapeScreen();setInterval(()=>{scraped = scraped.concat(scrapeScreen().filter((tweet)=>{for(let scrapedTweet of scraped){if(scrapedTweet.username == tweet.username && scrapedTweet.tweetText == tweet.tweetText) return false;}return true;}));}, 500); //Scrape everything on the screen twice a secondwindow.scrollIntervalId = setInterval(function(){window.scrollBy(0, 1000);}, 500); //Scroll for me//http://bgrins.github.io/devtools-snippets/#console-save(function(console){console.save = function(data, filename){if(!data) {console.error('Console.save: No data')return;}if(!filename) filename = 'console.json'if(typeof data === "object"){data = JSON.stringify(data, undefined, '\t')}var blob = new Blob([data], {type: 'text/json'}),e = document.createEvent('MouseEvents'),a = document.createElement('a')a.download = filenamea.href = window.URL.createObjectURL(blob)a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)a.dispatchEvent(e)}})(console)setTimeout(()=>{clearTimeout(window.scrollIntervalId);delete window.scrollIntervalId;console.save(scraped, "TwitterScrape" + Date.now() + ".json");}, 60 * 1000 * 20); //Twenty minutes
const arithmeticProgression = (n, lim) =>Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );arithmeticProgression(5, 25); // [5, 10, 15, 20, 25]