Converting Celsius to Fahrenheit with Rust

July 20, 2024
0 comments Rust

Previously in this series:

  1. Converting Celsius to Fahrenheit with Python
  2. TypeScript
  3. Go
  4. Ruby
  5. Crystal

This time, in Rust:


fn c2f(c: i8) -> f32 {
    let c = c as f32;
    c * 9.0 / 5.0 + 32.0
}

fn is_mirror(a: i8, b: i8) -> bool {
    let a = massage(a);
    let b = reverse_string(massage(b));
    a == b
}

fn massage(n: i8) -> String {
    if n < 10 {
        return format!("0{}", n);
    } else if n >= 100 {
        return massage(n - 100);
    } else {
        return format!("{}", n);
    }
}

fn reverse_string(s: String) -> String {
    s.chars().rev().collect()
}

fn print_conversion(c: i8, f: i8) {
    println!("{}°C ~= {}°F", c, f);
}

fn main() {
    let mut c = 4;
    while c < 100 {
        let f = c2f(c);
        if is_mirror(c, f.ceil() as i8) {
            print_conversion(c, f.ceil() as i8)
        } else if is_mirror(c, f.floor() as i8) {
            print_conversion(c, f.floor() as i8)
        } else {
            break;
        }
        c += 12;
    }
}

Run it like this:


rustc -o conversion-rs conversion.rs && ./conversion-rs

and the output becomes:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

Converting Celsius to Fahrenheit with Crystal

July 19, 2024
0 comments Ruby

Previously in this series:

  1. Converting Celsius to Fahrenheit with Python
  2. TypeScript
  3. Go
  4. Ruby

Crystal?

Crystal is a general-purpose, object-oriented programming language. With syntax inspired by Ruby, it's a compiled language with static type-checking.


def c2f(c)
    c * 9.0 / 5 + 32;
end

def is_mirror(a, b)
    massage(a).reverse == massage(b)
end

def massage(n)
    if n < 10
        "0#{n}"
    elsif n >= 100
        massage(n - 100)
    else
        n.to_s
    end
end

def print_conv(c, f)
    puts "#{c}°C ~= #{f}°F"
end

(4...100).step(12).each do |c|
    f = c2f(c)
    if is_mirror(c, f.ceil.to_i)
        print_conv(c, f.ceil.to_i)
    elsif is_mirror(c, f.floor.to_i)
        print_conv(c, f.floor.to_i)
    else
        break
    end
end

And this is its diff with the Ruby version:


<     if is_mirror(c, f.ceil)
<         print_conv(c, f.ceil)
<     elsif is_mirror(c, f.floor)
<         print_conv(c, f.floor)
---
>     if is_mirror(c, f.ceil.to_i)
>         print_conv(c, f.ceil.to_i)
>     elsif is_mirror(c, f.floor.to_i)
>         print_conv(c, f.floor.to_i)

Run it like this:


crystal conversion.cr

or build and run:


crystal build -o conversion-cr conversion.cr
./conversion-cr

and the output becomes:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

Converting Celsius to Fahrenheit with Ruby

July 18, 2024
0 comments Ruby

This is a continuation of Converting Celsius to Fahrenheit with Python, and TypeScript, and Go but in Ruby:


def c2f(c)
    c * 9.0 / 5 + 32;
end

def is_mirror(a, b)
    def massage(n)
        if n < 10
            "0#{n}"
        elsif n >= 100
            massage(n - 100)
        else
            n.to_s
        end
    end
    massage(a).reverse == massage(b)
end

def print_conv(c, f)
    puts "#{c}°C ~= #{f}°F"
end

(4...100).step(12).each do |c|
    f = c2f(c)
    if is_mirror(c, f.ceil)
        print_conv(c, f.ceil)
    elsif is_mirror(c, f.floor)
        print_conv(c, f.floor)
    else
        break
    end
end

Run it like this:


ruby conversion.rb

and the output becomes:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

Converting Celsius to Fahrenheit with Go

July 17, 2024
0 comments Go

This is a continuation of Converting Celsius to Fahrenheit with Python, and TypeScript, but in Go:


package main

import (
    "fmt"
    "math"
)

func c2f(c int) float64 {
    return float64(c)*9/5 + 32
}

func isMirror(a int, b int) bool {
    return reverseString(massage(a)) == massage(b)
}

func massage(n int) string {
    switch {
    case n < 10:
        return fmt.Sprintf("0%d", n)
    case n >= 100:
        return massage(n - 100)
    default:
        return fmt.Sprintf("%d", n)
    }
}

func reverseString(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func printConversion(c int, f int) {
    fmt.Println(fmt.Sprintf("%d°C ~= %d°F", c, f))
}

func main() {
    for c := 4; c < 100; c += 12 {
        var f = c2f(c)
        if isMirror(c, int(math.Ceil(f))) {
            printConversion(c, int(math.Ceil(f)))
        } else if isMirror(c, int(math.Floor(f))) {
            printConversion(c, int(math.Floor(f)))
        } else {
            break
        }
    }
}

Run it like this:


go run conversion.go

or build and run:


go build -o conversion-go conversion.go
./conversion-go

and the output becomes:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

Converting Celsius to Fahrenheit with TypeScript

July 16, 2024
0 comments Bun, JavaScript

This is a continuation of Converting Celsius to Fahrenheit with Python, but in TypeScript:


function c2f(c: number): number {
  return (c * 9) / 5 + 32;
}

function isMirror(a: number, b: number) {
  function massage(n: number) {
    if (n < 10) return `0${n}`;
    else if (n >= 100) return massage(n - 100);
    return `${n}`;
  }
  return reverseString(massage(a)) === massage(b);
}

function reverseString(str: string) {
  return str.split("").reverse().join("");
}

function printConversion(c: number, f: number) {
  console.log(`${c}°C ~= ${f}°F`);
}

for (let c = 4; c < 100; c += 12) {
  const f = c2f(c);
  if (isMirror(c, Math.ceil(f))) {
    printConversion(c, Math.ceil(f));
  } else if (isMirror(c, Math.floor(f))) {
    printConversion(c, Math.floor(f));
  } else {
    break;
  }
}

And when you run it:


❯ bun run conversion.ts
4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

Converting Celsius to Fahrenheit with Python

July 12, 2024
0 comments Python

Here's a useful mnemonic for remembering how to convert Celsius to Fahrenhait(*):

  • Start at 4°C
  • Add +12 each time
  • Flip the C in mirror, with some additional fudging

For example, 4°C is 04°C. Mirror image of "04" is "40". So 4°C equals 40°F.
And when there's a 1 in front, as in 125°F, look at that as 100 + 25°F. Mirror of 25°F is 52°C. So 52°C equals 125°F.

In Python it can be tested like this:


import math


def c2f(c):
    return c * 9 / 5 + 32


def is_mirror(a, b):
    def massage(n):
        if n < 10:
            return f"0{n}"
        elif n >= 100:
            return massage(n - 100)
        else:
            return str(n)

    return massage(a)[::-1] == massage(b)


def print_conv(c, f):
    print(f"{c}°C ~= {f}°F")


for i in range(4, 100, 12):
    f = c2f(i)
    if is_mirror(i, math.ceil(f)):
        print_conv(i, math.ceil(f))
    elif is_mirror(i, math.floor(f)):
        print_conv(i, math.floor(f))
    else:
        break

When you run that you get:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F

(*) If you can't remember F = C × 9/5 + 32 or, perhaps, remember it but can't compute the arithmetic easily.

In TypeScript, how to combine known and unknown keys to an object

July 3, 2024
0 comments JavaScript

More than happy to be informed of a better solution here! But this came up in a real-work situation and I "stumbled" on the solution by more or less guessing.

In plain JavaScript, you have an object which you know you set certain keys on. But because this object is (ab)used for a templating engine, we also put keys/values on it that are not known in advance. In our use case, these keys and booleans came from parsing a .yml file which. It looks something like this:


// Code simplified for the sake of the example

const context = {
  currentVersion: "3.12", 
  currentLanguage: "en",
  activeDate: someDateObject,
  // ... other things that are values of type number, bool, Date, and string
  // ...
}
if (someCondition()) {
  context.hasSomething = true
}

for (const [featureFlag, truth] of Object.entries(parseYamlFile('features.yml')) {
  context[featureFlag] = truth
}

const rendered = render(template: { context })

I don't like this design where you "combine" an object with known keys with a spread of unknown keys coming from an external source. But here we are and we have to convert this to TypeScript, the clock's ticking!

Truncated! Read the rest by clicking the link below.

Rate my golf swing (June 2024)

July 1, 2024
0 comments Golf

Never done this before but I thought it could be fun.

Things to keep in mind, I'm 45 years old and have only played for 2-3 years. My handicap is 8. I have a coach who has given me 5+ things to keep in mind, and I usually think only of 1-2 when I swing out on the course, and maybe 2-3 when I'm practicing on the mat.

What I'm currently working on is to not move the right hip too much to my right, but to instead load the power into the right thigh. I'm also trying to not bend my left (glove) hand but have a straight line from the underarm to the knuckles. The other thing I'm trying really hard to do is to move the club far out to my right in the first 20-30° with extended arms, rather than lifting the club up by my hands.

I'm super-far from an expert and I see lots of flaws compared to the pros. There's plenty of stuff still on my plate with the things I know I need to work on. Truth be told, at the moment, the thing I'm working on the most isn't swing mechanics but all mental; take it easy, and don't try to smash it.

Simple object lookup in TypeScript

June 14, 2024
2 comments JavaScript

Ever got this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: string; bar: string; }'. No index signature with a parameter of type 'string' was found on type '{ foo: string; bar: string; }'.(7053)

Yeah, me too. What used to be so simple in JavaScript suddenly feels hard in TypeScript.

In JavaScript,


const greetings = {
  good: "Excellent",
  bad: "Sorry to hear",
}
const answer = prompt("How are you?")
if (typeof answer === "string") {
  alert(greetings[answer] || "OK")
}

To see it in action, I put it into a CodePen.

Now, port that to TypeScript,

Truncated! Read the rest by clicking the link below.

Search GitHub issues by title, only

May 31, 2024
0 comments GitHub

tl;dr You can search GitHub issues specifically only in the title by adding in:title.

Suppose you go to a GitHub repository's Issue list. If you search, it will find issues that match your search in any field. For example:

Finding 70 issues by dialog

70 issues found

Now, add in:title to the search input:

Truncated! Read the rest by clicking the link below.