Skip to content

Instantly share code, notes, and snippets.

View adambene's full-sized avatar

Adam Bene adambene

View GitHub Profile
function distinctPreserveOrder(items) {
return [...new Set(items)];
}
import sys
def distinct_preserve_order_py37(items):
assert sys.version_info >= (3, 7), 'Please use Python 3.7 or above for this code.'
return list(dict().fromkeys(items).keys())
def distinct_preserve_order(items):
seen = set()
result = list()
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return list(result)
def distinct_set(items):
result = set()
for item in items:
# Checking is not needed, because the list.add() method is idempotent
result.add(item)
return list(result)
@adambene
adambene / distinct_naive.py
Created July 1, 2020 19:32
Distinct items in list, naive implementation
def distinct_naive(items):
"""
This naive implementation returns distinct elements of a list.
"""
results = list()
# iterate through all items
for item in items:
# append item to results if not member yet
if not item in results:
@adambene
adambene / distinct_naive_verbose.py
Last active July 1, 2020 19:04
Distinct items in list, naive and verbose implementation
def distinct_naive_verbose(items):
"""
This naive and verbose implementation returns distinct elements of a list.
"""
results = list()
# iterate through all items
for item in items:
member = False
def distinct_set_constr(items):
# The constructor of the set iterates through the item list in linear O(n) time:
# https://github.com/python/cpython/blob/3.9/Objects/setobject.c#L902-L909
return list(set(items))
@adambene
adambene / StripeClient.js
Created April 12, 2018 16:04
A partial Stripe client implementation for demo purposes.
const apiPrefix = 'https://api.stripe.com/v1';
const formBody = object => Object.keys(object).map(key => {
const encodedValue = encodeURIComponent(object[key])
const encodedKey = encodeURIComponent(key)
return `${encodedKey}=${encodedValue}`
}).join('&');
export default class StripeClient {
constructor(apiToken) {
@adambene
adambene / coroutine-runner.js
Last active March 8, 2018 17:23
Coroutine runner in JavaScript
const coroutine = nextValue => iterator => {
const { done, value } = iterator.next(nextValue);
if (done) {
return;
}
if (value.constructor === Promise) {
value.then(promiseValue => {
coroutine(promiseValue)(iterator);
@adambene
adambene / delays-with-callback-hell.js
Created March 8, 2018 17:09
Delays With Callback Hell in JavaScript
const delay = (ms, result, cb) => setTimeout(() => cb(result), ms);
function delays() {
delay(800, "Hello, I'm in a", a => {
console.log(a);
delay(400, "callback!", b => {
console.log(b);
});
});
}