DEV Community

Discussion on: Square a number: awful answers only

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Obviously, to square a number you first need to draw a square.

CSS

.parent {
    display: inline-flex;
    flex-direction: column;
}

.row {
    display: flex;
    flex-direction: row;
}

.cell {
    width: 1px;
    height: 1px;
    background: red;
}
Enter fullscreen mode Exit fullscreen mode

JS

function square(n) {
    const parent = document.createElement('div')
    parent.classList.add('parent')

    for (const _x of new Array(n)) {
        const row = document.createElement('div')
        row.classList.add('row')

        for (const _y of new Array(n)) {
            const cell = document.createElement('div')
            cell.classList.add('cell')

            row.appendChild(cell)
        }

        parent.appendChild(row)
    }

    document.body.appendChild(parent)

    const rect = parent.getBoundingClientRect()

    return rect.width * rect.height
}
Enter fullscreen mode Exit fullscreen mode

Limitations

It will only work for non-negative integer values of n.

Other than that, it's limited only by your browser's ability to render thousands upon thousands of divs.

Collapse
 
mellen profile image
Matt Ellen

I was hoping I'd see something like this 😁