Skip to content

Instantly share code, notes, and snippets.

View himanshupal's full-sized avatar
💬
kill -9 -1

Himanshu Pal himanshupal

💬
kill -9 -1
View GitHub Profile
@himanshupal
himanshupal / useClickAwayListener.ts
Created December 21, 2024 07:52
React hook to do some action on click away from given element
import { useEffect, useRef } from "react";
const useClickAwayListener = <T extends HTMLElement = HTMLDivElement>(callback: VoidFunction) => {
const ref = useRef<T>(null);
useEffect(() => {
const handleClick = (event: MouseEvent) => {
const target = event.target as T;
if (event.target !== ref.current) {
@himanshupal
himanshupal / client.mjs
Created August 20, 2024 20:40
Quick & Dirty SCRAM implementation
// @ts-check
import { completeAuth, initiateAuth } from "./server.mjs";
import { getClientKeyAndHash, getHMAC, getRandomBytes, hashPassword, xorBuffer } from "./utils.mjs";
/**
* @param {string} username
* @param {string} password
*/
export async function clientAuthentication(username, password) {
@himanshupal
himanshupal / generate-pushid.js
Created July 4, 2024 04:00 — forked from mikelehen/generate-pushid.js
JavaScript code for generating Firebase Push IDs
/**
* Fancy ID generator that creates 20-character string identifiers with the following properties:
*
* 1. They're based on timestamp so that they sort *after* any existing ids.
* 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs.
* 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly).
* 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the
* latter ones will sort after the former ones. We do this by using the previous random bits
* but "incrementing" them by 1 (only in the case of a timestamp collision).
*/
@himanshupal
himanshupal / main.rs
Created November 29, 2023 16:49 — forked from lu4nm3/main.rs
Tokio Async: Concurrent vs Parallel
use futures::StreamExt;
use std::error::Error;
use tokio;
use tokio::macros::support::Pin;
use tokio::prelude::*;
use tokio::time::{Duration, Instant};
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut multi_threaded_runtime = tokio::runtime::Builder::new()
.threaded_scheduler()
@himanshupal
himanshupal / multi_process_server.js
Created September 8, 2023 15:58
Simple express server that forks multiple processes so each process may answer individual requests in case of some blocking task; pm2 provides something similar that doesn't require to write this code at all.
const express = require("express");
const cluster = require("cluster");
const totalCPUs = require("os").cpus().length;
const port = 3000;
if (cluster.isMaster) {
console.log(`Number of CPUs is ${totalCPUs}`);
console.log(`Master ${process.pid} is running`);
@himanshupal
himanshupal / getWindows_continuous.ts
Last active July 22, 2023 05:02
Some helpful functions for React & iterators
/** Continuous windows as in carousel */
export const getWindows = <T>(data: T[], size = 5) => ({
acc: 0,
*[Symbol.iterator]() {
const length = data.length;
const array: T[] = [];
for (let i = 0; i < size; ++i) {
array.push(data[this.acc + i >= length ? this.acc + i - length : this.acc + i]);
}
if (this.acc >= length) this.acc = 1;
@himanshupal
himanshupal / useReducer_example.tsx
Created June 10, 2023 17:47
Typed example of React useReducer hook
import type { Reducer } from 'react'
import { Fragment, useReducer } from 'react'
interface IReducerState {
name: string
age: number
}
type IReducerAction =
| {
import { useEffect, useRef, useState } from 'react'
import { minPanelWidth } from '@/constants'
import style from './styles.module.less'
interface ISplitViewProps {
leftChild: React.ReactNode
rightChild: React.ReactNode
}
const SplitView: React.FC<ISplitViewProps> = ({ leftChild, rightChild }) => {
@himanshupal
himanshupal / BytesToType.sol
Created June 2, 2023 05:14
Alternative solution for bytes memory to any data type conversion
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MyToken is ERC20, ERC20Burnable, Pausable, Ownable {
constructor() ERC20("MyToken", "MTK") {}
@himanshupal
himanshupal / bit-meddler.ts
Created April 23, 2023 02:31
Types & helper function added for bit-meddler
const INT_MAX = ~(1 << (32 - 1))
const ITSAKINDOFMAGIC = [
0x3,
0x6,
0x9,
0x1d,
0x36,
0x69,
0xa6, // 2 to 8