Skip to content

Instantly share code, notes, and snippets.

View distinctPreserveOrder.js
function distinctPreserveOrder(items) {
return [...new Set(items)];
}
View distinct_preserve_order_py37.py
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())
View distinct_preserve_order.py
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)
View distinct_set.py
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 Jul 1, 2020
Distinct items in list, naive implementation
View distinct_naive.py
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 Jul 1, 2020
Distinct items in list, naive and verbose implementation
View distinct_naive_verbose.py
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
View distinct_set_constr.py
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 Apr 12, 2018
A partial Stripe client implementation for demo purposes.
View StripeClient.js
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 Mar 8, 2018
Coroutine runner in JavaScript
View coroutine-runner.js
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 Mar 8, 2018
Delays With Callback Hell in JavaScript
View delays-with-callback-hell.js
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);
});
});
}