Skip to content

Instantly share code, notes, and snippets.

@ziyoung
Last active May 12, 2023 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziyoung/89a8d1730d9b24f0af0d5b36a7ef3e70 to your computer and use it in GitHub Desktop.
Save ziyoung/89a8d1730d9b24f0af0d5b36a7ef3e70 to your computer and use it in GitHub Desktop.
泛泛而谈
const { EventEmitter } = require('event-emitter');
function mapAsync(iterable, mapper, option) {
// consumer 控制 concurrency
}
function filterAsync(iterable, filterer) {
// promise 控制
}
const map = {
x1: Promise.resolve(1),
x2: Promise.reject({
a: 1,
b: 2
})
}
function flatten() {}
class Queue extends EventEmitter {
constructor() {
super()
}
f() {
this.emit('xxx')
}
}
// 二进制数
var i = 200
i.toString(2)
var j = 0xff
j.toString(2)
// 移位 由于是双精度数,移位之后值更大了
(i << 2)
(j >> 2)
// byte 范围内,可以用 &,将高位的丢弃
(j >> 2) & 0xff
/*
var a byte = 0b001
var max byte = 0xff
var i = 0xff
var j uint = 0xff
log.Printf("i is %b, i is %b", i, j)
*/
/**
* 通过 Blob 可以动态加载资源:API 接口或者手动创建资源
* https://zh.javascript.info/blob
*/
async function main() {
const content = await fetch('url').then(r => r.blob());
// https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
window.open(url);
// URL.revokeObjectURL(url);
}
{
const script = document.createElement('script');
const content = `import _ from 'https://esm.sh/lodash';
const m = window._dynamic_module || {}
m.lodash = _
`
const url = URL.createObjectURL(new Blob([content], {
type: 'text/javascript'
}))
script.src = url;
script.type = 'module'
script.addEventListener('load', load)
function load() {
console.log('module load success')
this.remove()
}
document.head.appendChild(script)
}
const globby = require("globby");
/***
* extensions 对 * 不生效
**/
/*
paths [
'dist/200.html',
'dist/index.html',
'dist/assets/index.ccce2ca3.css',
'dist/assets/index.e9a3c359.js'
]
paths1 [
'200.html',
'200.txt',
'demo1.pdf',
'index.html',
'assets/index.ccce2ca3.css',
'assets/index.e9a3c359.js'
]
**/
(async function() {
const paths = await globby('dist', {
expandDirectories: {
extensions: ['html', 'css', 'js'],
},
})
console.log('paths', paths);
const paths1 = await globby(['*', 'assets'], {
expandDirectories: {
extensions: ['html', 'css', 'js'],
},
cwd: 'dist'
})
console.log('paths1', paths1)
})()

整体预览

buffer、logger

多个 goroutine 控制之间的 context

数据库操作

对 docker 机器,数据库实例之间的抽象 (conn) 直接做很多事情的

数据处理与转换

import _ from 'lodash'

// 聚合
_.group()


// 比较差异
_.difference([0, 1, 2, 3],[1, 2, 3, 5, 6]) // [0]

// 求交集∩
_.intersection([0, 1, 2, 3],[1, 2, 3, 5, 6]) // [1, 2, 3]
const through2 = require('through2');
function getReplaceStream(searchValue, replaceValue, options) {
let tail = ''
return through2(options, function transform(chunk, encoding, callback) {
const current = tail + chunk
const data = current.split(searchValue);
const lastIndex = data.length - 1;
const last = data[lastIndex];
const index = last.length - 1;
data[lastIndex] = last.slice(0, -index);
tail = last.slice(-index);
this.push(data.join(replaceValue))
callback()
}, function flush(callback) {
this.push(tail)
callback()
})
}
const r1 = getReplaceStream("__VAN_STATIC_BASE_PATH__", "some_special_url")
for (let i = 100; i <= 120; i++) {
r1.write(String.fromCharCode(i).repeat(10))
if (i > 110) {
r1.write('__VAN_STATIC_BASE_PATH__')
}
}
r1.write('\n')
r1.end()
r1.pipe(process.stdout)
const { Transform } = require('stream');
class ReplaceStream extends Transform {
constructor(searchValue, replaceValue, options) {
super(options)
this.searchValue = searchValue
this.replaceValue = replaceValue
this.retain = ""
}
_transform(chunk, encoding, callback) {
const current = this.retain + chunk
const pieces = current.split(this.searchValue);
const last = pieces.slice(-1)[0]
// 只需要处理剩余的字符串
const tailLength = this.searchValue.length - 1
this.retain = last.slice(-tailLength)
// 最后一个要去掉一些值
pieces[pieces.length - 1] = last.slice(0, -tailLength)
this.push(pieces.join(this.replaceValue))
callback()
}
_flush(callback) {
this.push(this.retain)
callback()
}
}
const r1 = new ReplaceStream("__VAN_STATIC_BASE_PATH__", "some_special_url")
for (let i = 100; i <= 120; i++) {
r1.write(String.fromCharCode(i).repeat(10))
if (i > 110) {
r1.write('__VAN_STATIC_BASE_PATH__')
}
}
r1.write('\n')
r1.end()
r1.pipe(process.stdout)
/***
* 对于一般文本处理场景,RegExp 与 magic-string 可以实现对字符串的快速编辑
*/
import MagicString from 'magic-string'
const regexp = /require\('([^']+)'\)\.default/g
while (true) {
const result = reg.exec(content)
if (!result) {
break
}
const [value, filepath] = result;
const { index } = result;
out.overwrite(index, index + value.length, JSON.stringify(filepath));
}
/**
* 当然 MagicString 还有其他的 api,
* 比如 append, prepend
**/
console.log(out.toString())

Network

Bash

curl 的一些用法

curl http://www.example.com:3000 --resolve www.example.com:3000:127.0.0.1
curl --unix-socket /var/run/docker.sock http://example.com/v1.26/containers/friendly_margulis/stats\?stream\=0
var inProgress = {};
var dataWebpackPrefix = "user-trace:";
// loadScript function to load a script via script tag
__webpack_require__.l = (url, done, key, chunkId) => {
if(inProgress[url]) { inProgress[url].push(done); return; }
var script, needAttach;
if(key !== undefined) {
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++) {
var s = scripts[i];
if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
}
}
if(!script) {
needAttach = true;
script = document.createElement('script');
script.charset = 'utf-8';
script.timeout = 120;
if (__webpack_require__.nc) {
script.setAttribute("nonce", __webpack_require__.nc);
}
script.setAttribute("data-webpack", dataWebpackPrefix + key);
script.src = url;
}
inProgress[url] = [done];
var onScriptComplete = (prev, event) => {
// avoid mem leaks in IE.
script.onerror = script.onload = null;
clearTimeout(timeout);
var doneFns = inProgress[url];
delete inProgress[url];
script.parentNode && script.parentNode.removeChild(script);
doneFns && doneFns.forEach((fn) => (fn(event)));
if(prev) return prev(event);
};
var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
script.onerror = onScriptComplete.bind(null, script.onerror);
script.onload = onScriptComplete.bind(null, script.onload);
needAttach && document.head.appendChild(script);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment