Kotlin's text.chunked in TypeScript

How to use

Install via yarn add locutus and import: import { chunked } from 'locutus/kotlin/text/chunked'.

Or with CommonJS: const { chunked } = require('locutus/kotlin/text/chunked')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1chunked('kotlin', 2)['ko', 'tl', 'in']
2chunked('abcdefg', 3)['abc', 'def', 'g']
3chunked('', 4)[]

Notes

  • Splits a string into consecutive chunks of at most size, like Kotlin text chunked.

Here's what our current TypeScript equivalent to Kotlin's text.chunked looks like.

export function chunked(str: string, size: number): string[] {
// discuss at: https://locutus.io/kotlin/text/chunked/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Splits a string into consecutive chunks of at most size, like Kotlin text chunked.
// example 1: chunked('kotlin', 2)
// returns 1: ['ko', 'tl', 'in']
// example 2: chunked('abcdefg', 3)
// returns 2: ['abc', 'def', 'g']
// example 3: chunked('', 4)
// returns 3: []

const source = String(str)
const width = Math.trunc(Number(size))
if (!Number.isFinite(width) || width <= 0) {
throw new RangeError('chunked(): size must be a positive integer')
}

const out: string[] = []
for (let i = 0; i < source.length; i += width) {
out.push(source.slice(i, i + width))
}
return out
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 2 Kotlin functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Kotlin stdlib documentation.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Kotlin text functions


Star