Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active August 21, 2021 16:18
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 YonatanKra/e92395daae7e47a28b89faeda63c8a55 to your computer and use it in GitHub Desktop.
Save YonatanKra/e92395daae7e47a28b89faeda63c8a55 to your computer and use it in GitHub Desktop.
function calculateSquare(matrix, chunkSize, randomFactor) {
const half = chunkSize / 2;
for (let y = 0; y < matrix.length; y += half) {
for (let x = (y + half) % chunkSize; x < matrix.length; x += chunkSize) {
const BOTTOM = matrix[y + half] ? matrix[y + half][x] : null;
const LEFT = matrix[y][x - half];
const TOP = matrix[y - half] ? matrix[y - half][x] : null;
const RIGHT = matrix[y][x + half];
const { count, sum } = [BOTTOM, LEFT, TOP, RIGHT].reduce(
(result, value) => {
if (isFinite(value) && value != null) {
result.sum += value;
result.count += 1;
}
return result;
},
{ sum: 0, count: 0 }
);
matrix[y][x] = sum / count + randomInRange(-randomFactor, randomFactor);
}
}
return matrix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment