Last active
March 9, 2020 16:31
-
-
Save d0ruk/fc4d696c83003d0c126e91ac724567bd to your computer and use it in GitHub Desktop.
JS snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Takes a promise and transform it to a cancelable promise by adding a "cancel" method | |
* @param {Promise} promise Promise to make cancelable | |
* @return {Promise} Cancelble promise | |
*/ | |
export const makePromiseCancelable = promise => { | |
let hasCanceled_ = false; | |
const wrappedPromise = new Promise((resolve, reject) => { | |
promise.then(val => | |
hasCanceled_ ? reject({ isCanceled: true }) : resolve(val) | |
); | |
promise.catch(error => | |
hasCanceled_ ? reject({ isCanceled: true }) : reject(error) | |
); | |
}); | |
return { | |
promise: wrappedPromise, | |
cancel() { | |
hasCanceled_ = true; | |
} | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log("1000,".repeat(10).split(",").slice(0,10)); // 12 | |
const arr = "1000,".repeat(10).split(",").slice(0,10).map(elem => Number(elem)); //arr of 10 Number's |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const consoleSave = 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, 4); | |
} | |
var blob = new Blob([data], { type: "text/json" }); | |
var e = document.createEvent("MouseEvents"); | |
var 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); | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// unify because compliance | |
module.exports = { | |
on: function(el, eventType, func) { | |
if (window.addEventListener) { | |
el.addEventListener(eventType, func, false); | |
} else { | |
el.attachEvent("on" + eventType, func); | |
} | |
}, | |
off: function(el, eventType, func) { | |
if (window.removeEventListener) { | |
el.removeEventListener(eventType, func, false); | |
} else { | |
el.detachEvent("on" + eventType, func); | |
} | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// require('core-js/modules/es7.symbol.async-iterator'); | |
const axios = require("axios"); | |
const Promise = require("bluebird"); | |
const base = "http://jsonplaceholder.typicode.com"; | |
const arr = ["/posts/1", "/todos/1"]; | |
const getResources = endpoints => ({ | |
[Symbol.iterator]: () => ({ | |
next: () => ({ value: 42, done: false }) | |
}), | |
[Symbol.asyncIterator]: () => ({ | |
next: () => { | |
if (endpoints.length === 0) { | |
return Promise.resolve({ done: true }); | |
} | |
return axios | |
.get(base + endpoints.shift()) | |
.then(res => ({ value: res.data, done: false })) | |
.catch(console.error); | |
} | |
}) | |
}); | |
(async () => { | |
for await (const data of getResources(arr)) { | |
console.log(data); | |
} | |
})(); | |
for (const i of getResources()) { | |
console.log(i); | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { bold, red, green, blue } = require("chalk"); | |
const Koa = require("koa"); | |
const app = new Koa(); | |
const Router = require("koa-router"); | |
let home = new Router(); | |
let page = new Router(); | |
let router = new Router(); | |
let delay = (dt, bool) => async (ctx, next) => { | |
const start = new Date(); | |
let p = new Promise((res, rej) => { | |
setTimeout(() => { | |
res(); | |
}, dt); | |
}); | |
await p; | |
await next(); | |
const ms = new Date() - start; | |
console.log(`${bool ? red.bold(ms) : green.bold(ms)} ms elapsed`); | |
}; | |
home.get("/", async ctx => { | |
let html = ` | |
<ul> | |
<li><a href="/page/hello">/page/hello</a></li> | |
<li><a href="/page/404">/page/404</a></li> | |
</ul> | |
`; | |
ctx.body = html; | |
}); | |
page | |
.get("/404", async ctx => { | |
ctx.body = Math.random(); | |
}) | |
.get("/hello", async ctx => { | |
ctx.body = Math.random(); | |
}); | |
router.use("/", delay(1000, true), home.routes(), home.allowedMethods()); | |
router.use( | |
"/page", | |
delay(2000, false), | |
delay(1000, false), | |
page.routes(), | |
page.allowedMethods() | |
); | |
// app.use(delay(5000)); | |
app.use(router.routes()).use(router.allowedMethods()); | |
app.listen(3000, () => console.log(green.bold("listening at 3000"))); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
window.addEventListener("resize", resizeThrottler, false); | |
var resizeTimeout; | |
function resizeThrottler() { | |
// ignore resize events as long as an actualResizeHandler execution is in the queue | |
if (!resizeTimeout) { | |
resizeTimeout = setTimeout(function() { | |
resizeTimeout = null; | |
// The actualResizeHandler will execute at a rate of 15fps | |
actualResizeHandler(); | |
}, 66); | |
} | |
} | |
function actualResizeHandler() { | |
// handle the resize event | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from "lodash"; | |
import fetch from "node-fetch"; | |
import delay from "delay"; | |
const servers = [ | |
"http://www.sevengramscaffe.com", | |
"http://www.hernanparra.co", | |
"http://www.thetimeandyou.com", | |
"http://www.luchoycarmelo.com" | |
]; | |
pingServers(servers).then(function(failedServers) { | |
for (const url in failedServers) { | |
console.log(`${url} failed ${failedServers[url]} times`); | |
} | |
}); | |
// https://gist.github.com/talkol/c2d67646b0f594bf46ee0f138c2d1b56 | |
function pingServers(servers) { | |
return _.reduce( | |
servers, | |
(failedServersAccumulator, url) => { | |
return failedServersAccumulator.then(failedServers => { | |
return _.reduce( | |
_.range(3), | |
failuresAccumulator => { | |
return failuresAccumulator.then(delay(10000)).then(failures => { | |
return fetch(url).then(response => { | |
return response.ok ? failures : failures + 1; | |
}); | |
}); | |
}, | |
Promise.resolve(0) | |
).then(failures => { | |
if (failures > 0) failedServers[url] = failures; | |
return failedServers; | |
}); | |
}); | |
}, | |
Promise.resolve({}) | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const request = require("request"); | |
const cottage = require("cottage"); | |
const bodyParser = require("koa-bodyparser"); | |
const serve = require("koa-static"); | |
const fs = require("fs"); | |
const path = require("path"); | |
let appDir = path.dirname(require.main.filename); | |
let setting = require("./setting.json"); | |
const app = cottage(); | |
app.use(bodyParser()); | |
app.use(serve(".")); | |
/** | |
* Get User's Real username. It needs for when logging mentions. | |
* | |
* @param token Slack Token | |
* @param userId User's unique ID in slack. | |
* @returns {Promise} Promise of Response. (for Generator) | |
*/ | |
function getUserName(token, userId) { | |
let url = `https://slack.com/api/users.info?token=${token}&user=${userId}`; | |
return new Promise(function(fulfill, reject) { | |
request.get(url, { json: true }, function(err, res, body) { | |
if (err) reject(err); | |
else fulfill(body.user.name); | |
}); | |
}); | |
} | |
function formatText(str, len) { | |
function string(str, len) { | |
var s = "", | |
i = 0; | |
while (i++ < len) s += str; | |
return s; | |
} | |
return string("0", len - str.length) + str; | |
} | |
function writeToFile(path, data) { | |
fs.exists(path, function(exists) { | |
if (exists) | |
fs.appendFile(path, data, "UTF-8", function(err) { | |
if (err) return console.log(err); | |
}); | |
else | |
fs.writeFile(path, data, "UTF-8", function(err) { | |
if (err) return console.log(err); | |
}); | |
}); | |
} | |
// HTTP POST /logger | |
// Register this link for Slack Outgoing Webhook. | |
app.post("/logger", function*(req) { | |
let userName = req.body.user_name; | |
let text = req.body.text; | |
let channelName = req.body.channel_name; | |
let timestamp = req.body.timestamp; | |
let date = new Date(timestamp * 1000); | |
let formatDate = `${d.getFullYear()}${formatText( | |
String(d.getMonth() + 1), | |
2 | |
)}${formatText(String(d.getDate()), 2)}`; | |
let regexp = text.match(/<@(U[A-Z0-9]{8})>/g); | |
let userIds = | |
regexp != undefined | |
? regexp.map(obj => | |
obj | |
.replaceAll("<", "") | |
.replaceAll(">", "") | |
.replaceAll("@", "") | |
) | |
: []; | |
var data = `[${formatDate}] ${userName}: ${text}\r\n`; | |
var userNames = {}; | |
for (let userId of userIds) | |
userNames[userId] = yield getUserName(setting.token, userId); | |
for (let userName in userNames) | |
if (userNames.hasOwnProperty(userName)) | |
data = data.replaceAll(userName, userNames[userName]); | |
writeToFile(`${appDir}/logs/${channelName}.log`, data); | |
}); | |
app.listen(4000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment