Split Binary Data with Search Data using Google Apps Script

Gists

This is a sample script for splitting the binary data with search data using Google Apps Script.

Sample script

/**
 * Split byteArray by a search data.
 * @param {Array} baseData Input byteArray of base data.
 * @param {Array} searchData Input byteArray of search data using split.
 * @return {Array} An array including byteArray.
 */
function splitByteArrayBySearchData_(baseData, searchData) {
  if (!Array.isArray(baseData) || !Array.isArray(searchData)) {
    throw new Error("Please give byte array.");
  }
  const search = searchData.join("");
  const bLen = searchData.length;
  const res = [];
  let idx = 0;
  do {
    idx = baseData.findIndex(
      (_, i, a) => [...Array(bLen)].map((_, j) => a[j + i]).join("") == search
    );
    if (idx != -1) {
      res.push(baseData.splice(0, idx));
      baseData.splice(0, bLen);
    } else {
      res.push(baseData.splice(0));
    }
  } while (idx != -1);
  return res;
}

// Please run this function.
function main() {
  const sampleString = "abc123def123ghi123jkl";
  const splitValue = "123";

  const res1 = splitByteArrayBySearchData(
    ...[sampleString, splitValue].map((e) => Utilities.newBlob(e).getBytes())
  );
  const res2 = res1.map((e) => Utilities.newBlob(e).getDataAsString());

  console.log(res1); // [[97,98,99],[100,101,102],[103,104,105],[106,107,108]]
  console.log(res2); // ["abc","def","ghi","jkl"]
}

 Share!