Skip to content

Instantly share code, notes, and snippets.

View ardeshireshghi's full-sized avatar

Ardeshir Eshghi ardeshireshghi

View GitHub Profile
@ardeshireshghi
ardeshireshghi / css-specificity.js
Last active January 25, 2024 00:10
This function takes the CSS selector text and calculates specificity. It does not take into account inline style and important specificity rules and only relies on the `selectorText`
function updateSpecificity(selector, currentSpecificity) {
const newSpecificity = [...currentSpecificity];
if (isSelectorId(selector)) {
newSpecificity[0] += 1;
return newSpecificity;
}
if (
isSelectorClass(selector) ||
@ardeshireshghi
ardeshireshghi / ScoreSortedSet.ts
Last active November 1, 2023 03:37
This is a simple implementation of a sorted set based on score and unique values
function findScoreIndexOrClosest<T>(
arr: [score: number, value: T][],
score: number,
): [matched: boolean, index: number] {
if (arr.length === 1) {
return arr[0][0] === score
? [true, 0]
: arr[0][0] > score
? [false, 0]
: [false, 1];
import { createHash, randomBytes } from "crypto";
interface INode<T = any> {
id: number;
data: Map<string, T>;
hash: string;
}
interface IHashRing {
nodes: INode<any>[];
@ardeshireshghi
ardeshireshghi / random-hex.sh
Created December 15, 2022 20:16
Create a random hex string 8 chars
cat /dev/urandom | head -1 | shasum | awk '{print $1}' | cut -c 1-8
function PriorityQueue() {
this.collection = [];
}
PriorityQueue.prototype = {
enqueue([item, priority]) {
let indexToBePlacedAt = -1;
for (let i = 0; i < this.collection.length; i++) {
const [, itemPriority] = this.collection[i];
const isNewItemHigherPriority = priority < itemPriority;
@ardeshireshghi
ardeshireshghi / app-container.js
Created October 18, 2022 16:29
A very naive solution for Dependency Injection
function createAppContainer() {
const bindingsMap = new Map();
const appContainer = {
bind(abstractClass, concreteClassOrFn) {
bindingsMap.set(abstractClass, concreteClassOrFn);
},
make(ClassToCreate, ...constructorArgs) {
const argTypes = ClassToCreate.argTypes || [];
'''Cache class for LRU'''
KEY_NOT_EXIST_VALUE = 'key-not-exist'
class LRUCache:
'''
Least recently used cache
'''
import EventEmitter from 'events';
import { Worker } from 'worker_threads';
class CustomWorker extends Worker {
public isReady: boolean;
constructor(...args: ConstructorParameters<typeof Worker>) {
super(...args);
this.isReady = true;
}
/**
* Sidebar UI component
*
* Example:
const sidebar = new Sidebar({
direction:
window.innerWidth <= 400
? Sidebar.direction.BOTTOM
: Sidebar.direction.LEFT,
// Old school classic inheritence
function Shape(name) {
this.name = name;
}
Shape.prototype.getName = function() {
return this.name;
}