Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created December 3, 2023 18:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChathuraGH/5470281c8f6814d7c15ee45fc9319ac6 to your computer and use it in GitHub Desktop.
Save ChathuraGH/5470281c8f6814d7c15ee45fc9319ac6 to your computer and use it in GitHub Desktop.
String Chunker
function chunkString (str, len) {
const size = Math.ceil(str.length/len)
const r = Array(size)
let offset = 0
for (let i = 0; i < size; i++) {
r[i] = str.substr(offset, len)
offset += len
}
return r
}
// console.log(chunkString("helloworld", 3))
// => [ "hel", "low", "orl", "d" ]
// 10,000 char string
// const bigString = "helloworld".repeat(1000)
// console.time("perf")
// const result = chunkString(bigString, 3)
// console.timeEnd("perf")
// console.log(result)
// => perf: 0.385 ms
// => [ "hel", "low", "orl", "dhe", "llo", "wor", ... ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment