Skip to content

Instantly share code, notes, and snippets.

@inter-coder
Last active December 13, 2022 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inter-coder/6023282d75ebb0e06ed8d4d63dfee0ae to your computer and use it in GitHub Desktop.
Save inter-coder/6023282d75ebb0e06ed8d4d63dfee0ae to your computer and use it in GitHub Desktop.
Polyfill array object in order to enable the loop in steps
<html>
<body>
<span id='counter' style='position:fixed;bottom:10px;right:10px;color:white;background:black;padding:10px;'></span>
</body>
<script>
Object.defineProperty(Array.prototype,'onPassLast',{//function to execute after the last pass of the array element
get: function(){this.onPassLastFN(this)},
set: function(fn){this.onPassLastFN=fn;}
});
Object.defineProperty(Array.prototype,'loop',{//function that is executed during transition to a new array element
set: function(cb){
if(typeof cb == "function"){this.callBack=cb;}else{this.currentIndex=this.currentIndex+cb;};
this.currentIndex=this.currentIndex==undefined?0:this.currentIndex;
if(this.currentIndex>=this.length){
return this.onPassLast;
}else{
this.callBack!=undefined?this.callBack(this[this.currentIndex],this):false;
};
}
});
Object.defineProperty(Array.prototype,'next',{//move to the next element
get: function(){this.loop=1;}
});
Object.defineProperty(Array.prototype,'shuffle',{//shuffle a series of elements randomly
get: function(){this.sort((a, b) => 0.5 - Math.random());return this;}
});
Object.defineProperty(Array.prototype,'weightOfElements',{//determine the number of repetitions of the same elements in the sequence
get: function(){
let obj=this;
if(obj.woe==undefined)obj.woe={};
obj.forEach(function (x){
obj.woe[x]=obj.woe[x]==undefined?1:obj.woe[x]+1;
});
return obj.woe;
}
});
var ajax=function(url,cb){//a trivial version of Ajax, only for download data from a remote server
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cb(JSON.parse(xhttp.responseText));
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
var counter=document.getElementById("counter");
ajax("http://jsonplaceholder.typicode.com/photos",function(data){
data=data.slice(0, 50);//what the heck, I just need 50 elements :)
data.onPassLast=function(array){alert("finish!", JSON.stringify(array));}//on passed all elements, do this function
data.loop=function(element,array){
var img=document.createElement("img");
img.src=element.url;
img.style.width="100px";
img.onload=function(){
window.scrollTo(0,document.body.scrollHeight);//subtle touch
array.next;//and when the image is loaded move to next member of the series
counter.innerHTML=data.currentIndex+"/"+data.length;//Show me on counter
}
document.body.appendChild(img);
}
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment