diff --git a/src/App.svelte b/src/App.svelte index 0e0412e..4e4b501 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -9,36 +9,25 @@ let padding = 0; let addPadding = true; - $: matrix = - matrixHeight > 0 && matrixWidth > 0 - ? Array(matrixHeight) - .fill(1) - .map(() => Array(matrixWidth).fill(1)) - : [[]]; - - $: kernel = - kernelHeight > 0 && kernelWidth > 0 - ? Array(kernelHeight) - .fill(1) - .map(() => Array(kernelWidth).fill(1)) - : [[]]; - + $: matrix = initMatrix(matrixWidth, matrixHeight, 1); + $: kernel = initMatrix(kernelWidth, kernelHeight, 1); $: result = conv_2d(kernel, matrix, addPadding, padding); - function uniform_array(len, value) { - let arr = new Array(len); - for (let i = 0; i < len; ++i) - arr[i] = Array.isArray(value) ? [...value] : value; - return arr; + function initMatrix(width, height, value) { + return width > 0 && height > 0 + ? Array(Math.floor(height)) + .fill(value) + .map(() => Array(Math.floor(width)).fill(value)) + : [[]]; } function conv_2d(kernel, array, addPadding, padding = 0) { // source: https://stackoverflow.com/questions/64669531/2d-convolution-for-javascript-arrays - let result = uniform_array(array.length, uniform_array(array[0].length, 0)); let kRows = kernel.length; let kCols = kernel[0].length; let rows = array.length; let cols = array[0].length; + let result = initMatrix(cols, rows, 0); // find center position of kernel (half of kernel size) let kCenterX = Math.floor(kCols / 2); let kCenterY = Math.floor(kRows / 2);