@supriyo_biswas

def get_string(dct):
    if len(dct) == 0:
        return ''

    result = ['^']
    for index, key in enumerate(dct):
        value = dct[key]
        if index == 0:
            result.append(f'@^{key}={value}')
        else:
            result.append(f'@{key}={value}')

Negative bitshift

June 13, 2022 · C
#include <stdio.h>

union A {
    char c[4];
    int x;
};

int main() {
    union A a;
    a.x = 65536;
    

Nodejs net.Blocklist bug

updated June 09, 2022 · NodeJS
console.log('Node version ' + process.version)

const net = require('net')

const reservedIPBlocklist = new net.BlockList()
reservedIPBlocklist.addSubnet('1.1.1.1', 32, 'ipv4')

for (const ip of ["10.0.0.1", "1.1.1.1", "4.3.2.4", "27.192.11.1", 
"192.168.1.9"]) {
    console.log(ip, reservedIPBlocklist.check(ip, 'ipv4'))    
}

Doubly linked list implementation

updated May 31, 2022 · NodeJS
const assert = require('node:assert').strict

class Node {
  constructor(value) {
    this.value = value
    this.prev = null
    this.next = null
  }

  unlink() {
    if (this.prev !== null) {

Pagination items

May 13, 2022 · NodeJS
function getPaginationItems(x, n) {
  const result = []
  const start = Math.max(1, x - 2)
  const end = Math.min(start + 2, n)
  if (start > 1) {
    result.push(1)
  }
  if (start > 2) {
    result.push('...')
  }
  for (let i = start; i <= end; i++) {
// const data = `
// ---
// hello: world
// foo: bar
// ---
// hello: world
// ---

// # Some article title

// > "hello world"
function * chunk(iterable, maxSize) {
    let result = []
    for (const item of iterable) {
        result.push(item)
        if (result.length === maxSize) {
            yield result
            result = []
        }
    }
    if (result.length > 0) {
        yield result

Private fields in Javascript

updated May 01, 2022 · NodeJS
class Foo {
    #y
    constructor(x) {
        this.x = x
        this.#y = x * 2
    }
}

const f = new Foo(10)
console.log(f)
console.log(f.x)

Splitting an array in chunks

April 30, 2022 · NodeJS
function chunk(arr, maxSize) {
    const result = []
    for (let i = 0; i < arr.length; i += maxSize) {
        result.push(arr.slice(i, i + maxSize))
    }
    return result
}

function range(start, stop) {
    const result = []
    for (let i = start; i < stop; i++) {

"awaiting" in loops without async/await

updated May 01, 2022 · NodeJS
function foo(message, delay) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(`${message} after sleeping for ${delay}ms`)
            resolve()
        }, delay)
    })
}

// Instead of doing this:

Reading a file line by line

April 28, 2022 · NodeJS
const { writeFile } = require('fs/promises')
const { createReadStream } = require('fs')
const { createInterface } = require('readline')

const data = `
---
hello: world
foo: bar
---
hello: world
---

Extract YAML blocks from Markdown content (WIP)

updated April 29, 2022 · NodeJS
const data = `
---
hello: world
foo: bar
---
hello: world
---

# Some article title

> "hello world"

Indenting a string

April 27, 2022 · NodeJS
function indentString(str, n) {
    return str.split("\n").map(x => " ".repeat(n) + x).join("\n")
}

const data = `foo
bar
baz
  qux
buzz
`

Deferring promise execution

updated April 27, 2022 · NodeJS
async function foo(x) {
    console.log("foo", x)
}

async function bar(x) {
    throw new Error("bar" + x)
}

class DeferredPromiseExecutor {
    constructor() {
        this.calls = []

Avoiding callback hell

updated April 25, 2022 · NodeJS
function foo() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("foo")
        }, 100)
    })
}

function bar() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
package main

import (
    "fmt"
    "regexp"
)

func main() {
    s1 := "FooBar"
    s2 := "Foo/Bar"
    s3 := "foobar/"

UUID regex

updated April 15, 2022 · Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String[] uuids = {
            "8fff4739-5f85-452d-8955-b0b0ace74bf7",
            "a1234567-1023-4984-9429-029183c02b1",
            "a1234567-1023-4984-9429-029183c02b1f",
            "hello",
            "a8fff4739-5f85-452d-8955-b0b0ace74bf7",

Working with SimpleDateFormat

updated April 15, 2022 · Java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

class Main {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        
        System.out.println("Formatting a date");
        

Mocking classes

April 11, 2022 · Java
import java.util.*;
import java.lang.*;
import java.io.*;


class A {
    public void foo() {
        System.out.println("foo");
    }
}

Random user agent generator

updated April 10, 2022 · Python
import random

def make_safari_user_agent():
    result = 'Mozilla/5.0 '
    platform = random.randint(0, 1)
    if platform == 0:
        result += (
            '(Macintosh; Intel Mac OS X 10_%d_%d) AppleWebKit/605.1.15 ' +
            '(KHTML, like Gecko) Version/%d.%d Safari/605.1.15'
        ) % (
            random.randint(10, 15),