Skip to content

Instantly share code, notes, and snippets.

@jaquinocode
jaquinocode / markdown-details-collapsible.md
Created January 31, 2022 22:53 — forked from pierrejoubert73/markdown-details-collapsible.md
How to add a collapsible section in markdown.

A collapsible section containing markdown

Click to expand!

Heading

  1. A numbered
  2. list
    • With some
    • Sub bullets
@jaquinocode
jaquinocode / previous_current_iterator.py
Created September 1, 2020 18:02
A normal generator/iterator that additionally keeps track of the previous element in Python. Also includes an iterator to keep track of next (after) element as well.
from itertools import tee, chain
# ABC -> (None, A) (A, B) (B, C)
def prev_curr_iter(iterable):
a, b = tee(iterable)
return zip(chain([None], a), b)
# use case
for prev, curr in prev_curr_iter("ABC"):
print(f"{prev=}\t{curr=}")
@jaquinocode
jaquinocode / getDefault.js
Last active December 25, 2023 19:46
setdefault but for JavaScript. setdefault is a function in Python which can be used to get around using a defaultdict. Here I recreate the behavior in JavaScript.
const getDefault = (o, key, defaultVal) => key in o ? o[key] : o[key] = defaultVal
// Prototype version of above. Allows for usage: o.getDefault(key, def)
Object.defineProperty(Object.prototype, "getDefault", {
value: function(key, defaultVal) {
return key in this ? this[key] : this[key] = defaultVal
}
})
@jaquinocode
jaquinocode / indexOfMin.js
Last active August 25, 2020 21:07
Get the index of the minimum number in the array. For 2nd one, reduce replaces python's min w/ a key since we don't have that in js.
const indexOfMin = numbers => {
return numbers.indexOf(Math.min(...numbers))
}
@jaquinocode
jaquinocode / rangeForJavascript.js
Last active December 25, 2023 19:47
range function for JavaScript. range is a function that's central to Python that I've implemented in JS. Here, it's a generator just like how it is in Python. Works with negative number arguments.
function* range(start, stop, step=1) {
if(typeof stop === 'undefined') [start, stop] = [0, start]
for(let i = start; step > 0 ? i < stop : i > stop; i += step)
yield i
}
/*
[...range(0, 10, 2)]
[0, 2, 4, 6, 8]
@jaquinocode
jaquinocode / int_float_or_string_checker.py
Last active August 16, 2020 16:14
Checks if a string is an int, float, or string in a way that's dependable & readable.
def int_float_or_string(string):
try:
int(string) # strict and nice
return int
except ValueError:
# float() is too permissive, this is better
return float if is_strictly_float(string) else str
def is_strictly_float(string):
if string.startswith("-"):