Skip to content

Instantly share code, notes, and snippets.

View leihuang23's full-sized avatar
⛰️

Lei Huang leihuang23

⛰️
View GitHub Profile
@leihuang23
leihuang23 / cps_demo.js
Created July 31, 2020 10:20
Parsing and processing DOM nodes in a non-blocking way using CPS technique.
function traverse(node, processTask, continuation) {
processTask(node, function handleChildren() {
const children = node.childNodes;
function handleOne(i, len, continuation) {
if (i < len) {
traverse(children[i], processTask, function handleNext() {
handleOne(i + 1, len, continuation);
});
} else {
let timeout = null;
const queue = new Set();
function process() {
for (const task of queue) {
task();
}
queue.clear();
timeout = null;
}
@leihuang23
leihuang23 / detect-if-user-is-from-china.js
Last active May 30, 2022 11:25
Detect if the user is from China or other countries where Google is blocked
// This code is mostly useless. I put it here for
// the purpose of entertainment...
function detectIfUserIsFromChina() {
const img = new Image()
img.setAttribute("src", `https://www.google.com/favicon.ico?t=${Date.now()}`)
img.setAttribute("style", "width:0;height:0;visibility:hidden;")
document.body.appendChild(img)
return new Promise(res => {
img.onerror = () => res(true)
@leihuang23
leihuang23 / memoPromise.js
Created February 11, 2023 09:32
Cache promise result with support for expiring
/**
* @param asyncFn - A promise-returning function. e.g. an HTTP call.
* @param expiresIn - The number of milliseconds for the result from calling `asyncFn` to expire.
* @returns A memoized function that will always resolve to the first result of calling `asyncFn`,
* as long as the result has not expired.
*/
export function memoPromise(asyncFn, expiresIn) {
const emptyId = Symbol("empty")
const memo = {}
@leihuang23
leihuang23 / isCyclic.js
Created February 11, 2023 09:38
Detect cyclic object reference in JavaScript.
export default function isCyclic(object, seen = new WeakSet().add(object)) {
const props = getProps(object)
let len = props.length
while (len--) {
const value = object[props[len]]
if (value instanceof Object) {
if (seen.has(value)) {
return true
}