Files
rust/test/option.test.ts
T
2024-05-21 15:40:45 +02:00

71 lines
2.6 KiB
TypeScript

import {expect, test} from 'bun:test'
import {Option, State} from 'option'
test('Base case Some', () => {
const value = 12
const opt = Option.some(value)
const value2 = 1
const opt2 = Option.some(value2)
const handler_throw = () => {
throw new Error("Shouldn't happen")
}
expect(opt.is_some()).toBeTrue()
expect(opt.is_some_and(data => data === value)).toBeTrue()
expect(opt.expect("Shouldn't happen")).toBe(value)
expect(opt.unwrap()).toBe(value)
expect(opt.unwrap_or(0)).toBe(value)
expect(opt.unwrap_or_else(handler_throw)).toBe(value)
expect(opt.is_none()).toBeFalse()
expect(opt.map(data => data + 1).unwrap()).toBe(value + 1)
expect(opt.map_or(0, data => data + 1)).toBe(value + 1)
expect(opt.map_or_else(handler_throw, data => data + 1)).toBe(value + 1)
expect(opt.ok_or("Shouldn't happen").unwrap()).toBe(value)
expect(opt.ok_or_else(handler_throw).unwrap()).toBe(value)
expect(opt.and(opt2).unwrap()).toBe(value2)
expect(opt.and_then(data => Option.some(data + 1)).unwrap()).toBe(value + 1)
expect(opt.filter(data => data === value).unwrap()).toBe(value)
expect(opt.or(opt2).unwrap()).toBe(value)
expect(opt.or_else(handler_throw).unwrap()).toBe(value)
expect(opt.xor(Option.none()).unwrap()).toBe(value)
expect(opt.xor(opt2).is_none()).toBeTrue()
expect(opt.state).toBe(State.Some)
})
test('Base case None', () => {
const opt = Option.none<number>()
const value2 = 12
const opt2 = Option.some(value2)
const handler_throw = () => {
throw new Error("Shouldn't happen")
}
expect(opt.is_some()).toBeFalse()
expect(opt.is_some_and(handler_throw)).toBeFalse()
expect(() => opt.expect("Shouldn't happen")).toThrow()
expect(() => opt.unwrap()).toThrow()
expect(opt.unwrap_or(0)).toBe(0)
expect(opt.unwrap_or_else(() => 0)).toBe(0)
expect(opt.is_none()).toBeTrue()
expect(opt.map(handler_throw).is_none()).toBeTrue()
expect(opt.map_or(0, handler_throw)).toBe(0)
expect(opt.map_or_else(() => 0, handler_throw)).toBe(0)
expect(opt.ok_or(0).unwrap_err()).toBe(0)
expect(opt.ok_or_else(() => 0).unwrap_err()).toBe(0)
expect(opt.and(opt2).is_none()).toBeTrue()
expect(opt.and_then(handler_throw).is_none()).toBeTrue()
expect(opt.filter(handler_throw).is_none()).toBeTrue()
expect(opt.or(opt2).unwrap()).toBe(value2)
expect(opt.or_else(() => opt2).unwrap()).toBe(value2)
expect(opt.xor(Option.none()).is_none()).toBeTrue()
expect(opt.xor(opt2).unwrap()).toBe(value2)
expect(opt.state).toBe(State.None)
})