Skip to content

Instantly share code, notes, and snippets.

@ehgoodenough
Last active September 29, 2016 08:40
Show Gist options
  • Save ehgoodenough/97b078aebdb63df57468 to your computer and use it in GitHub Desktop.
Save ehgoodenough/97b078aebdb63df57468 to your computer and use it in GitHub Desktop.
var Firebase = require("firebase")
class Leaderboard {
constructor(firebaseURL) {
this.firebase = new Firebase(firebaseURL)
this.firebase.orderByChild("score").limitToLast(5).on("value", (value) => {
this.scores = value.val()
})
}
add(data) {
if(!data.name || data.name.length > 3) {
throw new Error("Requires a valid name.")
} else if(!data.score || isNaN(data.score)) {
throw new Error("Requires a valid score.")
} else {
this.firebase.push(data).setPriority(data.score)
}
}
get() {
return this.scores
}
}
@ehgoodenough
Copy link
Author

If you want to let your players share their highscores through an online leaderboard, but you don't want to initiate and maintain the servers, you can just use Firebase! It's a real-time data-store, and it's totally awesome.

screen shot 2015-12-11 at 10 34 17 am

I wrote this snippet for adding scores, and returning the top five scores.

@ehgoodenough
Copy link
Author

To use it, just pass it a URL to your firebase.

var leaderboard = new Leaderboard("https://ehgoodenough.firebaseio.com/scores")
leaderboard.add({name: "ACM", score: 300})
var scores = leaderboard.get()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment