Artem Tyurin

Functions as seen in Smalltalk

⚠️ Warning: this is an exploration of a language and not something suitable for the production code.

We start by defining our own indexOf function. It takes a string, a character, and a starting index:

function indexOf(s, char, startingAt) {
  // ...
}

Then the function call would like like

indexOf('The owls are not what they seem.', 'o', 5) // 14

It might be hard to understand what every parameter means just by looking at the call.

In JavaScript this problem is usually solved by passing an object:

function indexOf({ s, char, startingAt }) {
  // ...
}

indexOf({
  s: 'The owls are not what they seem.',
  char: 'o',
  startingAt: 5,
}) // 14

Let’s explore an alternative approach.

In English language you can say:

Give me the index of the character "o" in the string "The owls are not what they seem." starting at index 5.

Languages like Smalltalk and Objective-C give you an ability to encode this type of sentences in method signatures.

Here is an example Objective-C method signature:

- (int)changeColorToRed:(float)red green:(float)green blue:(float)blue;

Method call would like like this:

[myColor changeColorToRed:5.0 green:2.0 blue:6.0];

Okay, back to JavaScript.

Let’s imagine we have define function:

define(
  'indexOf<char>in<string>startingAt<index>',
  (char, string, index) => {
    // reuse native JS implementation
    return string.indexOf(char, index);
  }
);

The result of this is the ability to run the following expression:

indexOf({ char: 'o' })
.in({ string: 'The owls are not what they seem.' })
.startingAt({ index: 5 }) // 14

Reads like a proper english sentence, right?

I will hide the definition in case you want to try code it yourself.

function define(parameterDefinitionString, handler) {
  // ...
}

Posted April 24, 2017

See other notes


Blog comments powered by Disqus.

Contact me

Email, GitHub