Monday, 30 October 2017

Chomping through a string from the front.

I am quite keen on functional programming techniques, so I am sort of disappointed in myself today. I am disappointed because I have had to change the state of some data, but for the best of reasons considering the use case. I went so far as to write a class that did what I needed it to do without interfering with the original data, but that just felt wrong, as though I was hiding what I was doing and I am not sure if I should try to hide my guilt. On the upside, I did use recursion!

Anyway, my use case required some fragments of a string to be spat to a backend where they would then be stitched back together again. I could send the whole string in one go, but it could be arbitrarily large, so I need to chomp through it and spit each uniform chunk back to the server.

I spent ages thinking about it then, as is so often the case, I went to JSFiddle and wrote this:

const container = document.getElementById("data");
const ourString = "1234567";
const chunkSize = 2;

const sendChunk = (ourString) => {
    const chunk = ourString.substr(0, chunkSize);
    const div = document.createElement("div");
    div.textContent = `Sending: ${chunk}`;
    ourString = ourString.slice(chunkSize);
    if (ourString.length) {
    } else {
        const finalDiv = document.createElement("div");
        finalDiv.textContent = "All Done!";


Along with this simple bit of HTML:

<div id="data"></div>

Basically it uses substr and slice to extract and then remove a portion of the string. If the string still has a length it then repeats the process, otherwise it tells us we’re all done. Neat eh? I just wish it didn’t feel so dirty.

No comments:

Post a Comment