Skip to content

Instantly share code, notes, and snippets.

const arr = [1, 2, 1, 2, 3, 3, 4, 5]
arr.filter((e, i) => arr.indexOf(e) !== i)
// returns [1, 2, 3]
map = (fn, [head, ...tail]) =>
(head === undefined && tail.length < 1)
? []
: [fn(head), ...map(fn, tail)]
// https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
JSON.parse(JSON.stringify(...))
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
),
[]
)
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))
import scala.annotation.tailrec
def recursiveSum(f: Int => Int)(a: Int, b: Int): Int = {
if (a > b)
0
else
f(a) + recursiveSum(f)(a + 1, b)
}
def tailRecursiveSum(f: Int => Int)(a: Int, b: Int): Int = {
@ahafidi
ahafidi / seconds.js
Created December 6, 2018 08:36
Tiny JS snippet to convert time formatted as 'HH:MM:SS' to seconds
const seconds = time => time // formatted as 'HH:MM:SS'
.split(':')
.reverse()
.reduce((acc, val, i) => acc + val * 60 ** i, 0)
@ahafidi
ahafidi / filename.js
Created December 1, 2018 07:05
filename from pathname
const filename = pathname.replace(/^.*[\\\/]/g, '')
@ahafidi
ahafidi / tiny_gql_server.js
Created August 2, 2018 13:48
A Tiny GraphQL Server using Apollo Server.
const { ApolloServer, gql } = require('apollo-server')
// The GraphQL schema
const typeDefs = gql`
type Query {
"A simple type for getting started!"
foo: String
foofoo: Int
}
`
/**
*
* @param {string} text
*
* Return a plain JS object providing the number of occurrences of every word containing at least 3 characters from the text
*/
const wordOccurrences = (text) => { // functional programming version
return text
.split(' ')
.filter((token) => token.length > 2)