Skip to content

Instantly share code, notes, and snippets.

@llakewood
Last active May 23, 2016 20:42
Show Gist options
  • Save llakewood/722048de2a16250ceee4cd5113a6e2cc to your computer and use it in GitHub Desktop.
Save llakewood/722048de2a16250ceee4cd5113a6e2cc to your computer and use it in GitHub Desktop.
Scratch API 2.0
<div id="error"></div>
<content id="output"></content>
$(document).ready(function() {
scratchApp.init();
});
var scratchApp = {
init: function() {
scratchApp.settings = {
user: "vars_co"
};
//Reset view
scratchApp.cleanup();
//Where did you come from? Where are you going?
scratchApp.analyzeLocation();
},
cleanup: function() {
$('div').html('');
},
analyzeLocation: function() {
switch (window.location.hostname) {
case "s.codepen.io":
scratchApp.settings.informer = window.location.search.split('=')[1];
scratchApp.settings.typeOfLookup = "project";
scratchApp.prepData();
break;
default:
scratchApp.settings.typeOfLookup = "projectList";
scratchApp.prepData();
break;
}
},
prepData: function(flag) {
let s = scratchApp.settings;
let url = "https://api-staging.scratch.mit.edu/";
switch (s.typeOfLookup) {
case "project":
url += 'users/' + s.user + '/projects/' + s.informer;
break;
case "projectList":
default:
url += 'users/' + s.user + '/projects';
}
scratchApp.getData(url);
},
getData: function(url) {
let jqxhr = $.ajax(url)
.done(function(data) {
switch (scratchApp.settings.typeOfLookup) {
case "project":
scratchApp.advanceOneALevel(data);
break;
case "projectList":
scratchApp.filterAndRandomize(data);
break;
}
})
.fail(function(data) {
console.log("error");
});
},
advanceOneALevel: function(data) {
let thisLevel = data.description.match(/([#][level])\w+/g);
if (thisLevel) {
thisLevel = thisLevel.join('');
thisLevel = thisLevel.split('#level');
let nextLevel = parseInt(thisLevel[1], 11) + 1;
scratchApp.settings.loadLevel = '#level' + nextLevel;
scratchApp.settings.typeOfLookup = "projectList";
scratchApp.prepData();
}
},
filterAndRandomize: function(data) {
let hasLevel = '';
let inThislevel = [];
$.each(data, function(i) {
hasLevel = data[i].description.match(/([#][level])\w+/g);
if (hasLevel !== null) {
hasLevel = hasLevel.join('');
if (hasLevel === scratchApp.settings.loadLevel) {
let projectId = data[i].id;
inThislevel.push(projectId);
};
}
});
let randomizer = inThislevel[Math.floor(Math.random() * inThislevel.length)];
scratchApp.goToRandomNextLevel(randomizer);
},
goToRandomNextLevel: function(randomProject) {
window.open(
'https://scratch.mit.edu/projects/' + randomProject + '/'
//,'_blank'
);
}
};
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment