Skip to content

Instantly share code, notes, and snippets.

View kawaz's full-sized avatar
🏠
Working from home

Yoshiaki Kawazu kawaz

🏠
Working from home
View GitHub Profile
@kawaz
kawaz / csprng.js
Last active November 30, 2023 20:06
ブラウザのJavascriptで暗号論的にセキュアな疑似乱数を使って指定範囲の整数の乱数を得る方法。
/**
* a以上b以下の整数の乱数を生成する
* @param {number|bigint} a
* @param {number|bigint} b
* @returns {number|bigint}
*/
function getRandomIntBetween(a, b) {
if (b < a) {
// [a, b] = [b, a]
const t = a; a = b; b = t;
@kawaz
kawaz / tools.js
Last active October 31, 2023 08:21
よく使うJSの便利関数的な奴 tools.js
// タイムアウト付き setInterval
const setIntervalTimeout = (f, interval = 200, timeout = 5000, immediate = false) => {
immediate && setTimeout(f, 0)
const i = setInterval(f, interval)
const t = setTimeout(() => clearInterval(i), timeout)
return () => { clearInterval(i); clearTimeout(t) }
}
// タイムアウト付き setInterval の強化版(タブがバックグラウンドになってもサボらない)
const setIntervalTimeoutSuper = (f, interval = 200, timeout = 5000, immediate = false) => {
try {
@kawaz
kawaz / beep.js
Last active September 5, 2023 02:44
Web Audio API を使って beep 音を鳴らすサンプル。
const beep = (duration=200, frequency=440, gain=1.0) => new Promise((resolve, reject) => {
try {
const audioCtx = new AudioContext()
const oscNode = new OscillatorNode(audioCtx, {frequency, type:"square"})
const gainNode = new GainNode(audioCtx, {gain})
oscNode.onended = resolve
oscNode.connect(gainNode).connect(audioCtx.destination)
oscNode.start(audioCtx.currentTime)
oscNode.stop(audioCtx.currentTime + duration / 1000)
} catch(err){
@kawaz
kawaz / movingAverageFilter.js
Created July 27, 2023 05:06
データ列に対してmapすると移動平均が得られるフィルタ関数。chartjs が移動平均線の描画に対応してないっぽいが、これを噛ましてやれば自力で移動平均用のデータ列が作れる。
const movingAverageFilter = (ws=3) => {
if(!Number.isInteger(ws) || ws < 1) {
throw new Error(`Invalid window size. ws must be >=1. You entered: ws=${ws}.`)
}
let win = []
let sum = 0
let pos = 0
let tail = 0
return (head) => {
sum = sum + head - tail
@kawaz
kawaz / q.js
Last active June 14, 2023 03:16
document.querySelectorAll のショートハンド関数。NodeList じゃなくて配列で返してくれます。::shadow に自前対応済み!
// const q = (s,r)=>[...(r||document).querySelectorAll(s)];
const q = (selector,root) =>
selector.split(/::shadow\s*/)
.reduce((parents,selector,idx) =>
parents.flatMap(parent =>
selector=="" ? (idx==0?parent:parent.shadowRoot) : [...(idx==0?parent:parent.shadowRoot).querySelectorAll(selector)]
)
, [root||document]
)
@kawaz
kawaz / base64-cffunctions.js
Last active March 24, 2023 05:42
CloudFront Functions 内でコピペで使えるBASE64実装
// CloudFront Functions 内で利用可能なBASE64実装
function b64enc(b) {
var b64codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split("").map(s=>s.charCodeAt(0))
var pad = [0, 2, 1][b.length % 3]
// 入力バイト列(本来は 0xFF を超える charCode が含まれていたらエラーにすべきだが省略
var bCodes = (b + '\0'.repeat(pad)).split("").map(s=>s.charCodeAt(0))
// 出力用バイト列
var aCodes = new Uint8Array(bCodes.length / 3 * 4)
for(var i=0,j=0; i<b.length; i+=3,j+=4){
@kawaz
kawaz / select-finder-items.swift
Created February 8, 2023 06:47
Finderでファイルを選択状態にするスクリプト。複数も可。
#!/usr/bin/swift
import AppKit
let urls = CommandLine.arguments.dropFirst(1).map { URL(fileURLWithPath: $0) }
NSWorkspace.shared.activateFileViewerSelecting(urls)
@kawaz
kawaz / .tmux.conf
Created December 1, 2015 09:17
tpm auto install
if "test ! -d ~/.tmux/plugins/tpm" \
"run 'git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm'"
@kawaz
kawaz / analyzeCode.js
Last active October 12, 2022 00:11
javascriptのcodePointAtとcharCodeAtの使い方や文字数の数え方などの練習
const toCodeUnit = s => s.split("").map(u => `\\u${u.charCodeAt(0).toString(16).toUpperCase().padStart(4, 0)}`).join("")
const toCodePoint = s => [...s].map(p => `\\u{${p.codePointAt(0).toString(16).toUpperCase()}}`).join("")
const splitToVisualChars = s => [...s].reduce((c, p, i, a) => {
let description = p
if (p == "\u200D") {
// ZERO WITH JOINER
description = "ZWJ"
} else if ("\u{180B}" <= p && p <= "\u{180D}") {
// モンゴル文字専用のモンゴル自由字形選択子(3個)
description = `FVS${p.codePointAt(0) - 0x180B + 1}`
@kawaz
kawaz / noerror.js
Created March 3, 2022 03:23
ムシャクシャしてやった。今は反省している(午前の進捗ぅううう…)
    // おまじない
ᡸ=ᡸᡸ=>ᡸ
    // SyntaxErrorはもちろん、ランタイムエラーすら出さずに実行可能
ᡸ```
ᡸhi
ᡸ```