Skip to main content

Rings and Rods

0 likes • Nov 19, 2022 • 1 view
JavaScript
Loading...

More JavaScript Posts

kNearestNeighbors

0 likes • Nov 19, 2022 • 5 views
JavaScript
const kNearestNeighbors = (data, labels, point, k = 3) => {
const kNearest = data
.map((el, i) => ({
dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),
label: labels[i]
}))
.sort((a, b) => a.dist - b.dist)
.slice(0, k);
return kNearest.reduce(
(acc, { label }, i) => {
acc.classCounts[label] =
Object.keys(acc.classCounts).indexOf(label) !== -1
? acc.classCounts[label] + 1
: 1;
if (acc.classCounts[label] > acc.topClassCount) {
acc.topClassCount = acc.classCounts[label];
acc.topClass = label;
}
return acc;
},
{
classCounts: {},
topClass: kNearest[0].label,
topClassCount: 0
}
).topClass;
};
const data = [[0, 0], [0, 1], [1, 3], [2, 0]];
const labels = [0, 1, 1, 0];
kNearestNeighbors(data, labels, [1, 2], 2); // 1
kNearestNeighbors(data, labels, [1, 0], 2); // 0

permutations

0 likes • Nov 19, 2022 • 0 views
JavaScript
const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val,
])
),
[]
);
};
permutations([1, 33, 5]);
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]

stripe api json iteration

0 likes • Nov 18, 2022 • 0 views
JavaScript
var arr = [{
"success": true,
"data": [
{
"id": "ipi_1KrrbvDOiB2klwsKhuqUWqt1",
"object": "issuing.transaction",
"amount": -2743,
"amount_details": {
"atm_fee": null
},
"authorization": "iauth_1KrrbuDOiB2klwsKoFjQZhhd",
"balance_transaction": "txn_1KrrbwDOiB2klwsK1YkjJJRi",
"card": "ic_1Krqe5DOiB2klwsK44a35eiE",
"cardholder": "ich_1KrqL8DOiB2klwsKtBnZhzYr",
"created": 1650753567,
"currency": "usd",
"dispute": null,
"livemode": false,
"merchant_amount": -2743,
"merchant_currency": "usd",
"merchant_data": {
"category": "advertising_services",
"category_code": "7311",
"city": "San Francisco",
"country": "US",
"name": "Aeros Marketing, LLC",
"network_id": "1234567890",
"postal_code": "94103",
"state": "CA"
},
"metadata": {},
"type": "capture",
"wallet": null
},
{
"id": "ipi_1Krrbvc62B2klwsKhuqUWqt1",
"object": "issuing.transaction",
"amount": -9999,
"amount_details": {
"atm_fee": null
},
"authorization": "iauth_1KrrbuDOiB2klwsKoFjQZhhd",
"balance_transaction": "txn_1KrrbwDOiB2klwsK1YkjJJRi",
"card": "ic_1Krqe5DOiB2klwsK44a35eiE",
"cardholder": "ich_1KrqL8DOiB2klwsKtBnZhzYr",
"created": 1650753567,
"currency": "USD",
"dispute": null,
"livemode": false,
"merchant_amount": -9999,
"merchant_currency": "usd",
"merchant_data": {
"category": "fast_food",
"category_code": "7311",
"city": "San Francisco",
"country": "US",
"name": "Aeros Marketing, LLC",
"network_id": "1234567890",
"postal_code": "94103",
"state": "CA"
},
"metadata": {},
"type": "capture",
"wallet": null
}
]
}];
const reduced = arr.reduce((prev, curr) => {
prev.push({
amount: curr.data[0].merchant_amount,
id: curr.data[0].id,
currency: curr.data[0].currency,
category: curr.data[0].merchant_data.category
});
console.log(prev)
return prev;
}, []);

retryPromise.js

0 likes • Oct 20, 2023 • 12 views
JavaScript
//Retries maxRetries number of times, meaning that if you have 0, then it'll run the function once.
async function retryPromise(promiseFn, maxRetries = 3, delayOffset = 0, delayRandomRange = 0) {
return new Promise((resolve, reject) => {
promiseFn()
.then(resolve, (error) => { //On error
if (maxRetries <= 0) {
return reject(error);
} else {
if(delayRandomRange * Math.random() + delayOffset < 1.0){
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolve, reject);
}else{
return new Promise((resolveTwo, rejectTwo) => {
setTimeout(() => {
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolveTwo, rejectTwo);
}, delayRandomRange * Math.random() + delayOffset);
}).then(resolve, reject);
}
}
});
});
}
//Tests for that function.
//Returns a function that will fail numTimes times, then will return aValue
function functionThatReturnsAFunctionThatFailsACoupleTimes(numTimes, aValue){
return async function(){
if(numTimes == 0){
return aValue;
}
numTimes--;
throw false;
};
}
const SMALL_NUMBER = 10;
function testTest(failNumberOfTimes){
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(failNumberOfTimes, true);
//Test my test
for(let i = 0; i < (failNumberOfTimes * 2); ++i){
function evalTest(val){
let testTestFailedReason = "";
if(val === undefined){
testTestFailedReason = "Test test returned undefined for some reason.";
}
if((i + 1) > failNumberOfTimes){
if(val === true){
//We're good
}else{
testTestFailedReason = "Test test didn't return true when it should have.";
}
}else{
if(val === false){
//We're good
}else{
testTestFailedReason = "Test test didn't return false when it should have.";
}
}
testTestFailedReason = testTestFailedReason || "Test test passed test case";
console.log(testTestFailedReason, "at index", i, "where the function returned", val);
}
functionThatFailsACoupleTimes().then(evalTest, evalTest)
};
}
testTest(SMALL_NUMBER);
let testCaseCounter = 1;
const throwsNoError = [
(val)=>{
if(val == true){
console.log("Passed test case " + (testCaseCounter++));
}else{
console.error("Unexpected return value", val);
}
},
()=>{
console.error("It wasn't supposed to fail!")
}
]
const throwsError = [
(val)=>{
console.error("It wasn't supposed to succeed!", val);
},
(val)=>{
if(val == false){
console.log("Passed test case " + (testCaseCounter++));
}else{
console.error("Unexpected return value", val);
}
}
];
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2).then(...throwsError)
//Testing the delay. You'll have to wait a bit too.
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1, 500, 500).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2, 500, 500).then(...throwsError)

return array head

0 likes • Nov 19, 2022 • 0 views
JavaScript
const head = arr => (arr && arr.length ? arr[0] : undefined);
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined

Scrape twitter

0 likes • Sep 2, 2023 • 9 views
JavaScript
//Allegedly never tested on the twitter website
function 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 second
window.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 = filename
a.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