neverthrow icon indicating copy to clipboard operation
neverthrow copied to clipboard

Error in the example in readme

Open chandru89new opened this issue 9 months ago • 0 comments

import { getLines } from 'imaginary-parser'
// ^ assume getLines has the following signature:
// getLines(str: string): Result<Array<string>, Error>

// since the formatting is deemed correct by `getLines`
// then it means that `linesResult` is an Ok
// containing an Array of strings for each line of code
const linesResult = getLines('1\n2\n3\n4\n')

// this Result now has a Array<number> inside it
const newResult = linesResult.map(
  (arr: Array<string>) => arr.map(parseInt)
)

newResult.isOk() // true

Note this:

(arr: Array<string>) => arr.map(parseInt)

parseInt actually can take two params:

parseInt(a, b)
// a = the string to parse as an integer  
// b = the base (if not supplied, b=10 ie base 10)

So this function:

(arr: Array<string>) => arr.map(parseInt)

ends up passing the index to the parseInt as second parameter:

(arr: Array<string>) => arr.map((s,i) => parseInt(s,i))

which works fine for the first index in the array because parseInt(n,0) == n (n as number/int)

but starts behaving weirdly for other indices.

chandru89new avatar Mar 28 '25 12:03 chandru89new