From 8abe053e33c3d3b99d2d069fef11ef9f1402b168 Mon Sep 17 00:00:00 2001 From: Robert Attard Date: Wed, 13 Oct 2021 04:08:46 -0400 Subject: #238 : result returned from int.to_string_base and add int.to_baseN (#239) --- src/gleam/int.gleam | 70 +++++++++++++++++++++++++++++++++++++++++++++++++---- src/gleam_stdlib.js | 2 +- 2 files changed, 66 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/gleam/int.gleam b/src/gleam/int.gleam index 0df7397..6c280d6 100644 --- a/src/gleam/int.gleam +++ b/src/gleam/int.gleam @@ -62,21 +62,37 @@ if javascript { "../gleam_stdlib.js" "to_string" } +/// For use in to_base_string when base is outside of the allowed range. +pub type InvalidBase { + InvalidBase +} + /// Prints a given int to a string using the base number provided. +/// Supports only bases 2 to 36, for values outside of which this function returns an Error(InvalidBase). +/// For common bases (2, 8, 16, 36), use the to_baseN functions. /// /// ## Examples /// /// > to_base_string(2, 2) -/// "10" +/// Ok("10") /// /// > to_base_string(48, 16) -/// "30" +/// Ok("30") /// /// > to_base_string(48, 36) -/// "1C" +/// Ok("1C") /// -pub fn to_base_string(int, base) { - do_to_base_string(int, base) +/// > to_base_string(48, 1) +/// Error(InvalidBase) +/// +/// > to_base_string(48, 37) +/// Error(InvalidBase) +/// +pub fn to_base_string(int, base) -> Result(String, InvalidBase) { + case base >= 2 && base <= 36 { + True -> Ok(do_to_base_string(int, base)) + False -> Error(InvalidBase) + } } if erlang { @@ -89,6 +105,50 @@ if javascript { "../gleam_stdlib.js" "int_to_base_string" } +/// Prints a given int to a string using base2. +/// +/// ## Examples +/// +/// > to_base2(2) +/// "10" +/// +pub fn to_base2(int) { + do_to_base_string(int, 2) +} + +/// Prints a given int to a string using base8. +/// +/// ## Examples +/// +/// > to_base8(15) +/// "17" +/// +pub fn to_base8(int) { + do_to_base_string(int, 8) +} + +/// Prints a given int to a string using base16. +/// +/// ## Examples +/// +/// > to_base16(48) +/// "30" +/// +pub fn to_base16(int) { + do_to_base_string(int, 16) +} + +/// Prints a given int to a string using base16. +/// +/// ## Examples +/// +/// > to_base36(48) +/// "1C" +/// +pub fn to_base36(int) { + do_to_base_string(int, 36) +} + /// Takes an int and returns its value as a float /// /// ## Examples diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js index 158a571..96fa4f1 100644 --- a/src/gleam_stdlib.js +++ b/src/gleam_stdlib.js @@ -54,7 +54,7 @@ export function float_to_string(float) { } export function int_to_base_string(int, base) { - return int.toString(base); + return int.toString(base).toUpperCase(); } export function string_replace(string, target, substitute) { -- cgit v1.2.3