Skip to footer navigation.

« Oatmeal

Posts tagged JavaScript

Follow this tag's bespoke rss feed or return to the list of all tags.

My programming language odyssey

While I wouldn’t say I’m wicked adept at any one language, I’ve dipped my toes into many different languages. Here, I try to roughly recreate my programming language journey.

I can make websitez gud; HTML, CSS/SASS, JavaScript > CoffeeScript > TypeScript, and PHP

The web. A marvel, a terror. I started here, more out of ease of access than necessity, but was able to get far enough to make a career out of web dev. I should also add SQL to this list.

Elm is something I’d like to dip my toes into.

Want make thingz go brrrr; Common Lisp

I don’t honestly know how I first came to Common Lisp, I think through a blog post, or maybe a cute book. While I don’t use it much these days, I still carry a torch for it in my heart.

Want lovely tooling; SmallTalk

I sort of wish I’d never played with SmallTalk. It broke me. SmallTalk opened my eyes to a really integrated development environment.

Oh snap! Parenthesis are rad!; Clojure

Clojure remains my white whale. On paper it is the perfect language for me:

  • lots of parenthesis
  • good at web stuff
  • fine for game dev
  • friendly with emacs

But I’ve never felt cozy in it.

The JVM is hard, but scheme is rad!; a million flavors of scheme and scheme-like languages, (Chicken Gerbil s7 Racket Guile Chibi)

Parentheses baaaby! If I was forced to stick to a single language and never touch another, I’d probably pick a scheme…the question is then which scheme!?

Racket isn’t strictly a pure” scheme, but who cares and it can be…and has a bananas gigantic library.

Chibi is adorably tiny and the most fully featured R7RS scheme I’ve found.

Chicken has some great docs…and is called chicken,” I mean, come on!? That is lovely.

What about games though? I wanna make games!; Lua (especially using PICO-8 or Love2d)

I have in recent years become pretty jaded about the state of software and what most software is used for…but I love games, so, Lua is pretty rad for making games. Lua is also a really great teaching/learning language.

But I missing the parenthesis; Fennel

Yeah, but what if Lua was a lisp-like language?

I’ve found that many programming languages are made or broken by their community. Fennel has one of the friendliest, most supportive communities I’ve ever witnessed in a programming language.

This is neat, but what if I wanted weirder?; Janet

Janet would be another contender for a forever language — it is weird, sort of a Clojure clone, sort of a Lisp, but totally its own thing at the same time. It is tiny, portable, and fits into similar spaces that C does…but also not really. Janet is a beast utterly of its own…also the name of my grandma.

Hold up now! I said weirder!; BQN, APL, K

Alright, this was probably me going off the deep end…

Okay, too0ooo weird and my brain is goo; gforth, pforth, and lbforth

I adore languages that I can hold entirely in my head. A big thing that helps me hold a language in my head is limited semantics. You don’t get much more limited than Forth!

The ethos at the heart of Forth is clearly articulated by its inventor,

The concept that programming is something that you need special education to do is not right. It is something that is promoted by the priesthood.

— Chuck Moore

Hold those horses…I’m in love!; RetroForth

Readers of this blog will have seen me talk about Retro before…while it makes no sense as a forever language…here I am…I’m stricken…I’m totally lovesick for it. It is tiny, it is portable, it is well documented, it assumes literate programming as the norm!

That’s a mighty nice little vm you’ve got there; Uxntal

Like Forth, this is another system that strives to be pretty much completely understandable. A system that can be held in 1 person’s head…it also offers everything you need to make little graphical programs and games.

But what if assembly?; 6502 and z80 assembly

Again, this was me going off the deep end a little bit.

What if I wanted a job though?; C, C++, Go, Java, Kotlin, and Swift

Blergh — remember when I said that SmallTalk broke me? Yeah, that broken-ness really comes to rear its head when I try to use these gigantic enterprise languages that have terrible tooling (Go, C, and C++ are almost passable, but Kotlin and Swift are laughable).

I also once upon a time tried Rust but it literally melted a component on my laptop so I gave up.

Fuck it! Those are no fun! Go go gadget make your own programming language!; Guava

I mean…did I really make my own programming language? No. But, Guava does carry with it a lot of what I’ve liked about other languages along the way.


So, where next? What next? I’m a habitual breadth over depth kinda person. I wanna say it is time to go deep on one language…but…who knows!?

Notes on Big O Notation

Imagine we have 2 implementations of the same function. How do we know which one is best? This is what Big O helps with! Big O notation is a little bit like the Richter scale for code performance.

Write a function that calculates the sum of all numbers from 1 up to (and including) n.

function addUpToV1(n) {
    let total = 0;
    for (let i = 1; i <= n; i++) {
        total += i;
    }
    return total;
}

function addUpToV2(n) {
    return n * (n + 1) / 2;
}

These both work! But which is better? And what does better mean?

Faster, less memory usage, and more readable

…alas, readability tends to be the lowest ranked in this hierarchy ಥ_ಥ

Lets determine which one is faster! We’ll use performance.now() to help determine this.

let t1 = performance.now();
addUpToV1(1000000000);
let t2 = performance.now();
console.log(`Time Elapsed: ${(t2 - t1) / 1000} seconds.`);

let t3 = performance.now();
addUpToV2(1000000000);
let t4 = performance.now();
console.log(`Time Elapsed: ${(t4 - t3) / 1000} seconds.`);

While this process works, it isn’t heaps reliable and is a bit hairy to talk about because time is problematic. Different computers will record different time — margins are pretty much guaranteed to be different across computers. Also, for stuff like this, time isn’t useful because they’re both wicked quick — the smallest interval of measurable time isn’t small enough!

ENTER BIG O!

console.log('big O!');

Rather than counting time, lets count the number of operations!

What is an operation?

addUpToV2 does 3 operations:

  1. Multiplication
  2. Addition
  3. Division

Regardless of whatever value is passed for n, it’ll always do 3 operations.

addUpToV1, now, is a different story! The number of operations is tied to the value of whatever value is passed for n!

Don’t be heaps concerned with the exact number of operations — what is important here is to understand the big picture. Big O Notation is a way to formalize fuzzy counting. With it, we can talk about how the runtime of an algorithm grows as the inputs grow. It is an expression of the relationship between the size of input and runtime.

Big O is all about the broad trends.

Legit definition:

An algorithm is O(f(n)) if the number of simple operations the computer has to do is eventually less than a constant f(n), as n increases

Big O helps answer the question when n grows, how does it grow?”

Some general guidance to follow:

  • Constants don’t matter! O(500) is simplified to O(1), O(13n^2) -> O(n^2)
  • Smaller terms don’t matter! O(n+10) -> O(n), O(n^2+5n+8) -> O(n^2)
  • Arithmetic operations are constant
  • Variable assignment is constant
  • Accessing elements in an array (by index) or object (by key) is constant
  • In a loop the complexity is determined by the length of the loop multiplied by the the complexity of whatever is happening inside of the loop
// O(n), as n grows our runtime grows
function logAtLeast5(n) {
    for (var i = 1; i <= Math.max(5, n); i++) {
        console.log(i);
    }
}

// O(1), as n grows runtime grows, but is capped at 5 
function logAtMost5(n) {
    for (var i = 1; i <= Math.min(5, n); i++) {
        console.log(i);
    }
}

let t5 = performance.now();
logAtLeast5(30);
let t6 = performance.now();
console.log(`Time Elapsed: ${(t6 - t5) / 1000} seconds.`);

let t7 = performance.now();
logAtMost5(30);
let t8 = performance.now();
console.log(`Time Elapsed: ${(t8 - t7) / 1000} seconds.`);

Olophont.js

In Lord of the Rings there are creatures that look like giant elephants. JRR Tolkien named these creatures olophonts…” simply replacing every vowel in the word elephant with an o. Here is a javascript function to do the same thing.

function olophont(string) {
  let replaceVowels = "";
  for (let i = 0; i < string.length; i++) {
    if (!'aeiou'.includes(string[i])) {
      replaceVowels += string[i];
    } else {
      replaceVowels += 'o';
    }
  }
  return replaceVowels;
}

console.log(olophont('elephant'));
console.log(olophont('banana'));
console.log(olophont('chimpanzee'));
console.log(olophont('fish'));

dice.js 2.0

A little dice rolling class in JavaScript for all your dice rolling needs.

class diceRoller {

  constructor() {
    this.log = [];
  }

  validate(diceNotation) {
    const match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(diceNotation);
    if (!match) {
      throw "Invalid dice notation: " + diceNotation;
    } else {
      return match;
    }
  }

  parseDice(diceNotation) {
    const match = this.validate(diceNotation);
    if (match) {
      const diceInfo = {
        numberOfDice: typeof match[1] === "undefined" ? 1 : parseInt(match[1]),
        sidesOfDice: parseInt(match[2]),
        diceModifier: typeof match[3] === "undefined" ? 0 : parseInt(match[3])
      };
      return diceInfo;
    }
  }

  tallyRolls(diceData) {
    let total = 0;
    for (let i = 0; i < diceData.numberOfDice; i++) {
      total += Math.floor(Math.random() * diceData.sidesOfDice) + 1;
    }
    total += diceData.diceModifier;
    return total;
  }

  roll(humanInput) {
    const rollResult = this.tallyRolls(this.parseDice(humanInput));
    const rightNow = new Date();
    let logEntry = {
      "timestamp": rightNow.toISOString(),
      "input": humanInput,
      "result": rollResult
    }
    this.log.push(logEntry);
    return rollResult;
  }

};

And a quick example of how to use it,

// instantiate yo' players
const playerSarah = new diceRoller();
const playerEli = new diceRoller();

// play the game
playerSarah.roll('2d10-4');
playerEli.roll('2d12+12');
playerSarah.roll('1d12');
playerEli.roll('1d2');


// check the log!
console.log('==== Sarah\'s log ====');
playerSarah.log.forEach(logEntry => {
  console.log(logEntry.input + " : " + logEntry.result + " : " + logEntry.timestamp);
});

console.log('==== Eli\'s log ====');
playerEli.log.forEach(logEntry => {
  console.log(logEntry.input + " : " + logEntry.result + " : " + logEntry.timestamp);
});

In reply to: I have resigned as the WordPress accessibility team lead. Here is why. | Brad Frost

JavaScript is eating the world, and that has me just a bit worried. Designers and specialists of different stripes might not have the programming chops of a JavaScript engineer, but their perspectives are just as important to the success and health of a software product. I don’t like the idea of you must be this tall to ride” when it comes to participating in software projects. I think it’s important to consider approachability when building tools and choosing technologies.

In reply to: GitHub - KleoPetroff/react-webpack-boilerplate: Minimalistic ES6 React boilerplate with Hot Reloading using Webpack 4

The best one I’ve found, yet.

Hi, my name is Eli and today Javascript devoured me whole 🦖

In reply to: spectre and the end of langsec -- wingolog

The basis of language security is starting from a programming language with a well-defined, easy-to-understand semantics. From there you can prove (formally or informally) interesting security properties about particular programs.

Continuing…

But the Spectre and Meltdown attacks have seriously set back this endeavor. One manifestation of the Spectre vulnerability is that code running in a process can now read the entirety of its address space, bypassing invariants of the language in which it is written, even if it is written in a safe” language. This is currently being used by JavaScript programs to exfiltrate passwords from a browser’s password manager, or bitcoin wallets.

Javascript without closing semicolons makes me sad… ;(

A large part of my job boils down to fighting with Javascript carousel frameworks. Slick is the one I’ve had the best luck with so far. Anyone have any favorites or recommendations?

npm run start all day long

It is raining today, meaning today is a CSS and JS, kinda day. 🌧👾🔧