0

I'm working on a grid layout function. I'm about 1/2 way there and have hit a wall.

I am using a string and running a single RegExp function per box I'm placing in the grid to determine where it will fit (based on number of rows/columns it occupies). This works successfully. Demonstration:

function findSpace(columns, rows){
    var totalColumns = 4;
    var grid = "11002100020000200002";
    //1 represents occupied space, 0 empty space, and 2 a new line
    var reg = RegExp("(0{" + columns + "})(([0-2]{" + (totalColumns - columns + 1) + "})0{"+columns+"}){" + (rows-1) + "}");
    var i = grid.search(reg);
    return i.index;
}

Returns the index of the match, letting me know where in my grid this box will fall. See fiddle.

I fall short trying to replace the "0"s with "1"s. Doing grid.replace(reg, "1") of course replaces everything from the beginning of the match to the end with a single "1". I need to replace just the "0"s that will be occupied for row and column, each with a "1", and not any of the characters matched between.

This is an exercise in doing things differently. Yes, I could do this with an array data structure. What fun is that? I'm not looking for a "don't do it this way do it the way everyone else does" answer, I'm trying to determine the most efficient way to solve my scenario.

Thanks!

1 Answer 1

1

The String#replace method might be the ticket. If you pass a regular expression and a function as the second parameter, you can dynamically manipulate each match.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Sign up to request clarification or add additional context in comments.

1 Comment

That just might be the ticket, it's a good thought. I'll work on it and get back to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.