Skip to content

Instantly share code, notes, and snippets.

@abdulhannanali
Last active April 26, 2017 08:58
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 abdulhannanali/e4cc64c9248d93d824936f71fd90855d to your computer and use it in GitHub Desktop.
Save abdulhannanali/e4cc64c9248d93d824936f71fd90855d to your computer and use it in GitHub Desktop.
Pixel List defines a custom iterator to iterate the list of Pixel containing x and y coordinated in a sorted order based on their distance from (0, 0). Based on the idea in Getify's YDKS This and Object Prototypes Book to define a custom iterator
const Pixel = require('./pixel-it');
// Contains all the pixels within a list
const pixelList = []
// Custom iterator of object is accessed by using
// Symbol.iterator a computed property name
pixelList[Symbol.iterator] = function () {
// Defining a function for the custom iterator
const sortedList = sortList(this);
let it = 0;
return {
next: function () {
return {
value: sortedList[it++],
done: it > sortedList.length
}
}
}
}
const clone = a => a.map(v => v)
function sortList (pixelList) {
const clonedList = clone(pixelList);
return clonedList.sort((pixel1, pixel2) => {
const distance1 = distZero(pixel1);
const distance2 = distZero(pixel2);
if (distance1 > distance2) return 1;
else if (distance1 < distance2) return -1;
else if (distance1 === distance2) return 0;
})
}
function calcDist (pixel2, pixel1) {
return Math.sqrt(Math.pow(pixel2.x - pixel1.x, 2) + Math.pow(pixel2.y - pixel1.y, 2))
}
distZero = calcDist.bind({}, new Pixel(0, 0));
for (var i = 0; i < 50; i++) {
for (var j = 0; j < 50; j++) {
pixelList.push(new Pixel(i, j));
}
}
// This will iterate the pixel in a sorted order based on the function
// distZero to calculate the distance of all the pixels from point (0, 0) on the screen.
for (var pixel of pixelList) {
console.log(distZero(pixel));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment