Skip to content

Instantly share code, notes, and snippets.

View griffinmichl's full-sized avatar

Griffin Michl griffinmichl

View GitHub Profile
function sum(numbers, i = 0) {
if (i === numbers.length) {
return 0
}
return numbers[i] + sum(numbers, i+1)
}
console.log(sum([1,2,3,4,5]))
function sumTail(numbers, i = 0, sum = 0) {
function debounce(func, wait) {
let timeout
return function(...args) {
const context = this
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(context, args), wait)
}
}
function sayHello() {
// still wrong
function debounce(func, wait) {
let timeout
return (...args) => {
const context = this
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(context, args), wait)
}
}
function sayHello() {
console.log('My name is', this.name)
}
const amy = {
name: 'amy',
speak: debounce(sayHello),
}
amy.speak()
function sayHello(x) {
console.log(x)
}
const debouncedSayHello = debounce(sayHello, 100)
debouncedSayHello(1)
debouncedSayHello(2)
debouncedSayHello(3)
setTimeout(() => debouncedSayHello(4), 200)
// the wrong way
function debounce(func, wait) {
let timeout
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => func(...arg), wait)
}
}
const task1 = done => setTimeout(_ => {console.log('1'); done()}, 100)
const task2 = done => setTimeout(_ => {console.log('2'); done()}, 50)
const task3 = done => setTimeout(_ => {console.log('3'); done()}, 25)
const taskRunner1 = queue(1)
taskRunner1.push(task1)
taskRunner1.push(task2)
taskRunner1.push(task3)
// 1
function queue(concurrency = 1) {
let running = 0
const taskQueue = []
const runTask = (task) => {
running++
task(() => {
running--
if (taskQueue.length > 0) {
runTask(taskQueue.shift())
const fetchContent = (url) => {
const timeDelay$ = Rx.Observable.timer(1000);
const request$ = Rx.Observable.create(observer =>
fetch(url, { mode: 'no-cors' })
.then(json => {
console.log('test')
observer.onNext(json)
observer.onCompleted()
})
.catch(e => observer.onError())
const fetchContent = (url) =>
rx.Observable.create(observer =>
fetch(url)
.then(res => res.json())
.then(json => {
observer.onNext(json)
observer.onCompleted()
)
.catch(e => observer.onError())
)