Skip to content

Instantly share code, notes, and snippets.

val tolerance = 0.00001
def isCloseEnough(x: Double, y: Double): Boolean =
Math.abs((x - y) / x) / x < tolerance
def fixedPoint(f: Double => Double)(firstGuess: Double) = {
def iterate(guess: Double): Double = {
val next = f(guess)
if (isCloseEnough(guess, next))
const fibonacci = n =>
[...Array(n)].reduce(
(acc, val, i) => acc.concat( // concat returns the new acc
i > 1
? acc[i - 1] + acc[i - 2]
: i
),
[]
)
// https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
JSON.parse(JSON.stringify(...))
map = (fn, [head, ...tail]) =>
(head === undefined && tail.length < 1)
? []
: [fn(head), ...map(fn, tail)]
const arr = [1, 2, 1, 2, 3, 3, 4, 5]
arr.filter((e, i) => arr.indexOf(e) !== i)
// returns [1, 2, 3]
@ahafidi
ahafidi / zip.js
Last active September 27, 2021 12:41
some zip implementations
const zip = (...rows) =>
rows[0].map((_, i) => rows.map((row) => row[i]))
const zip2 = (arr, ...arrs) =>
arr.map((val, i) => arrs.reduce((acc, cv) => [...acc, cv[i]], [val]))
const zip3 = (...arrs) => {
let r = []
for (let i = 0; i < arrs.length; i++) {
const flattenDepth = (arr, depth = 1) =>
arr.reduce(
(acc, cv) => [
...acc,
...(depth === 0 || !Array.isArray(cv)
? [cv]
: flattenDepth(cv, depth - 1))
],
[]
);
const arrayCalculation = (specialArray, depth = 1) => {
const r = []
specialArray.forEach((e) => {
if (Number.isInteger(e))
r.push(e)
if (Array.isArray(e))
r.push(arrayCalculation(e, depth + 1))
})
return depth * r.reduce((acc, cv) => acc + cv, 0)
const findSmallestInterval = (numbers) => {
numbers.sort((a, b) => a - b)
let r = Number.MAX_SAFE_INTEGER
numbers.forEach((e, i) => {
if (i + 1 > numbers.length)
return
const d = Math.abs(e - numbers[i + 1])
const sleep = async (ms) => {
await new Promise(resolve => {
setTimeout(() => resolve(0), ms)
})
}
await sleep(2000)