Skip to content

Instantly share code, notes, and snippets.

View petergi's full-sized avatar
💭
Just Busy Living On The Side Of A Square

Peter Giannopoulos petergi

💭
Just Busy Living On The Side Of A Square
View GitHub Profile
// Checks if a date is the same as another date.
// - Use `Date.prototype.toISOString()` and strict equality checking (`===`) to check if the first date is the same as the second one.
const isSameDate = (dateA, dateB) =>
dateA.toISOString() === dateB.toISOString();
isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
function traverse(matrix) {
const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]];
const rows = matrix.length, cols = matrix[0].length;
const visited = matrix.map(row => Array(row.length).fill(false));
function dfs(i, j) {
if (visited[i][j]) {
return;
}
visited[i][j] = true;
// Finds the highest index at which a value should be inserted into an array in order to maintain its sort order, based on a provided iterator function.
//
// - Loosely check if the array is sorted in descending order.
// - Use `Array.prototype.map()` to apply the iterator function to all elements of the array.
// - Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted, based on the provided iterator function.
const sortedLastIndexBy = (arr, n, fn) => {
const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
const val = fn(n);
const index = arr
open System
open System.IO
open System.Threading.Tasks
let private readFileAsync (file:string) (f:byte[] -> 'a) =
async {
// Open stream
use stream = File.OpenRead(file)
// Async read, so we don't block on the thread pool
let rec insertions x = function
| [] -> [[x]]
| (y :: ys) as l -> (x::l)::(List.map (fun x -> y::x) (insertions x ys))
let rec permutations = function
| [] -> seq [ [] ]
| x :: xs -> Seq.concat (Seq.map (insertions x) (permutations xs))
open System
let getAge (d : DateTime) =
let d' = DateTime.Now
match d' > d with
| true ->
let months = 12 * (d'.Year - d.Year) + (d'.Month - d.Month)
match d'.Day < d.Day with
| true -> let days = DateTime.DaysInMonth(d.Year, d.Month) - d.Day + d'.Day
# Python's list comprehensions are awesome.
vals = [expression
for value in collection
if condition]
# This is equivalent to:
vals = []
for value in collection:
if condition:
vals.append(expression)
# "is" vs "=="
a = [1, 2, 3]
b = a
a is b
# True
a == b
# True
# Why Python Is Great:
# In-place value swapping
# Let's say we want to swap
# the values of a and b...
a = 23
b = 42
# The "classic" way to do it
# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
from collections import namedtuple
Car = namedtuple('Car', 'color mileage')
# Our new "Car" class works as expected:
my_car = Car('red', 3812.4)