Skip to content

Instantly share code, notes, and snippets.

View aherve's full-sized avatar

Aurélien aherve

View GitHub Profile
@aherve
aherve / testing.ts
Last active December 7, 2016 13:28
import { expect } from 'chai'
describe('Stuff', () => {
// -------THE CALLBACK WAY------- //
it('looks ugly with callbacks', (done) => {
User.count({}, (err, count) => {
if (err) { return done(err) }
expect(count).to.be.above(1)
User.findOne({}, (err, user) => {
if (err) { return done(err) }
// ----- Without async ----- //
function regularPlusOne (i: number): Promise<number> {
return new Promise(resolve => {
resolve(i + 1)
})
}
// ----- With async ----- //
async function plusOne (i: number): Promise<number> {
return i + 1
async function notSure (userId: string | null): Promise<null | User> {
if (!userId) { return null } // e.g. return void
const user = await User.findById(userId) // this return the result of the promise of findById
if (user) { return user }
throw 'User not found'
}
@aherve
aherve / await.ts
Last active December 7, 2016 10:54
async function demo (userId: string) {
try {
const user = await User.findById(user)
const result = await doSomethingAsync(user)
finalResult(user, result)
} catch (e) {
dealWithIt(e)
}
}
function demoPromise (userId) {
User
.findById(userId)
.then(user => {
doSomethingAsync(user)
.then(result => {
finalResult(user, result)
})
})
}
function demoPromise (userId) {
User
.findById(userId)
.then(doSomethingAsync) // doSomething will receive `user` as argument if everything goes smoothly
.catch(dealWithIt) // here we catch both the `findById` and `doSomethingAsync` errors at once
}
function demoCb (userId) {
User.findById(userId, (err, user) => {
if (err) { dealWithIt(err) }
doSomethingAsync(user, (err, result) => {
if (err) { dealWithIt(err) }
// and so it goes...
})
})
}
@aherve
aherve / out3.tsv
Last active December 6, 2016 14:22
1 chess 1.2
2 chess 1.7
1 go 1.4
2 go 1.0
1 hide-and-seek 8.0
3 hide-and-seek 2.7
#!/usr/bin/env ruby
class Reducer
attr_accessor :key, :game_type, :user_id
def initialize(key,value)
@key = key
#split the primary key to get user_id and game type:
@game_type,@user_id = key.split("|")
chess|1 1
chess|1 1
chess|2 1
chess|2 2
go|1 2
chess|1 1
go|1 1
go|1 1
chess|2 2
go|1 1