Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, August 10, 2026

Functional programming in JavaScript (12)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

Modularity lets us create code that spans multiple modules (technically: files).

But how it works under the hood? How do import and export actually work in a functional way? How it is possible to have cyclic dependencies between modules?

We are going to build a short example of three modules: A, B and Main. Modules A and B will depend on each other.

Let's start with the code:

// ==========================================
// Infrastructure
// ==========================================
const registry = {};

function registerModule(id, factoryFn) {
    registry[id] = {
        id,
        factoryFn,
        exports: {},        
        isEvaluated: false  
    };
}

function evaluateModule(id) {
    const mod = registry[id];
    
    if (mod.isEvaluated) {
        return mod.exports;
    }

    mod.isEvaluated = true;

    const _import = (dependencyName) => {
        return evaluateModule(dependencyName);
    };

    const _export = (name, fn) => {
        mod.exports[name] = fn;
    };

    mod.factoryFn(_import, _export);

    return mod.exports;
}

// ==========================================
// Example use
// ==========================================

// Module A (a.js) - cyclic dependency to B
registerModule('./a.js', (_import, _export) => {
    const _b = _import('./b.js');

    let valueA = "Wartość z A";

    _export('getA', () => valueA);
    _export('callB', () => "A calls B -> " + _b.getB() );
});

// Module B (b.js) - cyclic dependency to A
registerModule('./b.js', (_import, _export) => {
    const _a = _import('./a.js');

    let valueB = "Wartość z B";

    _export('getB', () => valueB);
    _export('callA', () => "B calls A -> " + _a.getA() );
});

// main module (main.js)
registerModule('./main.js', (_import, _export) => {
    const _a = _import('./a.js');
    const _b = _import('./b.js');

    console.log(_a.callB());
    console.log(_b.callA());
});

evaluateModule('./main.js');

Look how simple it is. We have a global registry of modules. Our register function just adds a module to the registry.

The only non trivial function here is the evaluation function. The function executes module's factory function.

Whenever we execute the import, we just recursively call the evaluation function. And this is where a problem with cyclic dependencies could possibly occur.

How do we prevent it?

    ...
    if (mod.isEvaluated) {
        return mod.exports;
    }

    mod.isEvaluated = true;

We check if module is already evaluated and if it is, we just return its exports - but the actual list of module's exports can possibly be empty at this point! In fact, the list of module's exports can be available only after the module initialization is complete!

That's why we only export functions and we call the evaluation of the main module only when the dependency graph is fully evaluated (all exports are available). If a module is imported multiple times (by other modules), its factory function is evaluated only once, all subsequent initializations terminate early.

Saturday, January 3, 2026

Functional programming in JavaScript (10)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

In the next blog entry, we continue the Church encoding of various language elements into JavaScript. We already did booleans, numbers, IF and recursion.

This time we'll do lists.

Lists can be implemented using pairs, a list of (1,2,3,4) is just (1, (2, (3, 4))), nested pairs. Other complex objects can be built on top of this idea.

If you need PAIR/FIRST/SECOND, just go back to the previous blog entry.

// NIL is a pair where the first element is TRUE (a flag for "I am empty")
const NIL    = PAIR(TRUE)(TRUE); 
const IS_NIL = l => FIRST(l); // Returns TRUE if it's NIL, FALSE if it's a real PAIR

// Re-defining PAIR for numbers to ensure FIRST(l) is always FALSE
const LIST_NODE = x => y => PAIR(FALSE)(PAIR(x)(y));
const HEAD = l => FIRST(SECOND(l));
const TAIL = l => SECOND(SECOND(l));

And that's it! We can define a list and an example operation on a list:

// Building the list: [1, 2, 3]
const list1 = LIST_NODE(ONE)(NIL);
const list2 = LIST_NODE(TWO)(list1);
const list3 = LIST_NODE(THREE)(list2); // This is [3, 2, 1]

// --- sum function 
const SUMLIST = Y(self => list => 
  IF (IS_NIL(list))
    (() => ZERO) 
    (() => ADD(HEAD(list))(self(TAIL(list)))));

console.log( toInt(SUMLIST(list3)) );

We could also have an auxiliary toArray function, similar to previous toInt and toBool:

const toArray = (list, elementConverter = (x => x)) => {
  const result = [];
  let current = list;

  // While IS_NIL is FALSE (using toInt to bridge the Church Boolean to JS)
  while (toInt(IS_NIL(current)) === 0) {
    // 1. Get the data from the current node
    const churchValue = HEAD(current);
    
    // 2. Convert and push to our JS array
    result.push(elementConverter(churchValue));
    
    // 3. Move to the next node
    current = TAIL(current);
  }
  
  return result;
};

console.log( toArray( list3, toInt ) ); // [3,2,1]

How about MAP or other list operations that just transform list to another list?

Well, using all the tools we have, it's easy:

const MAP = Y(self => f => list =>
  IF (IS_NIL(list))
    (() => NIL)
    (() => LIST_NODE(f(HEAD(list)))(self(f)(TAIL(list)))));

// Example: Double every number in the list
const DOUBLE = n => ADD(n)(n);
const doubledList = MAP(DOUBLE)(list3); // [6, 4, 2]

console.log("First item doubled:", toInt(HEAD(doubledList))); // 6
console.log("Total:", toInt(SUMLIST(doubledList)));           // 12

And that's it. You can continue from here on your own. Define other operators, write more high level functions. Experiment.

Just to give you some more ideas:

const LEQ = m => n => IS_ZERO(SUB(m)(n));  // no negative numbers, subtracting from ZERO stays at ZERO!
const GT = m => n => NOT(LEQ(m)(n));
const LT = m => n => NOT(LEQ(n)(m));

console.log( toBool( LEQ(TWO)(FOUR)) ); // true
console.log( toBool( LEQ(FOUR)(TWO)) ); // false
console.log( toBool( LEQ(TWO)(TWO)) );  // true
console.log( toBool( LT(TWO)(FOUR)));   // true
console.log( toBool( LT(FOUR)(TWO)));   // false
console.log( toBool( LT(FOUR)(TWO)) );  // false

A complete code of all examples of Church encoding:

const TRUE  = a => b => a;
const FALSE = a => b => b;

const AND = p => q => p(q)(p);
const OR  = p => q => p(p)(q);
const NOT = p => p(FALSE)(TRUE);

const toBool = f => f(true)(false);

console.log( toBool( TRUE ) );
console.log( toBool( FALSE ) );

console.log( toBool( AND(TRUE)(TRUE) ) );
console.log( toBool( AND(FALSE)(TRUE) ) );
console.log( toBool( AND(TRUE)(FALSE) ) );
console.log( toBool( AND(FALSE)(FALSE) ) );

console.log( toBool( OR(TRUE)(TRUE) ) );
console.log( toBool( OR(FALSE)(TRUE) ) );
console.log( toBool( OR(TRUE)(FALSE) ) );
console.log( toBool( OR(FALSE)(FALSE) ) );

console.log( toBool( NOT(TRUE) ) );
console.log( toBool( NOT(FALSE) ) );

const ZERO  = f => x => x;
const ONE   = f => x => f(x);
const TWO   = f => x => f(f(x));
const THREE = f => x => f(f(f(x)));

const toInt = n => n(i => i + 1)(0);

console.log( toInt( ZERO ) );
console.log( toInt( ONE ) );
console.log( toInt( TWO ) );
console.log( toInt( THREE ) );

const SUCC  = n => f => x => f(n(f)(x));

const FOUR = SUCC(THREE);
console.log( toInt( FOUR ) );

const ADD   = m => n => f => x => m(f)(n(f)(x));
const MUL   = m => n => f => m(n(f));

console.log( toInt( ADD(TWO)(THREE) ) );
console.log( toInt( MUL(TWO)(THREE) ) );

//const POW = m => n => n(m);
const POW = m => n => f => n(m)(f);

console.log( toInt( POW(TWO)(FOUR) ) );

// --- lists
const PAIR   = x => y => f => f(x)(y);
const FIRST  = p => p(TRUE);
const SECOND = p => p(FALSE);

// A helper that takes a pair (n, n+1) and returns (n+1, n+2)
const PHI = p => PAIR(SECOND(p))(SUCC(SECOND(p)));

// PRED starts at (0, 0), applies PHI 'n' times, then takes the FIRST element
const PRED = n => FIRST(n(PHI)(PAIR(ZERO)(ZERO)));

// SUBTRACT(m)(n) is just applying PRED to m, n times.
const SUB = m => n => n(PRED)(m);

console.log( toInt( PRED(FOUR) ) );
console.log( toInt( SUB(FOUR)(TWO) ) );
console.log( toInt( SUB(TWO)(FOUR) ) );

// --- if
const IF = p => a => b => p(a)(b)();

// --- recursion
const Y = f => (x => x(x))(x => f(y => x(x)(y)));

const IS_ZERO = n => n(x => FALSE)(TRUE);

const EQUALS = m => n => 
  AND (IS_ZERO(SUB(m)(n))) 
      (IS_ZERO(SUB(n)(m)));

// --- THE FAC FUNCTION ---
const FAC = Y(self => n =>
  IF (EQUALS(n)(ONE))               // if n == 1
    (() => ONE)                     //    return 1
    (() => MUL(n)(self(PRED(n))))); //    else return n * fac(n-1)

console.log( toInt( FAC(FOUR) ) );

// NIL is a pair where the first element is TRUE (a flag for "I am empty")
const NIL    = PAIR(TRUE)(TRUE); 
const IS_NIL = l => FIRST(l); // Returns TRUE if it's NIL, FALSE if it's a real PAIR

// Re-defining PAIR for numbers to ensure FIRST(l) is always FALSE
const LIST_NODE = x => y => PAIR(FALSE)(PAIR(x)(y));
const HEAD = l => FIRST(SECOND(l));
const TAIL = l => SECOND(SECOND(l));

// Building the list: [1, 2, 3]
const list1 = LIST_NODE(ONE)(NIL);
const list2 = LIST_NODE(TWO)(list1);
const list3 = LIST_NODE(THREE)(list2); // This is [3, 2, 1]

// --- sum list
const SUMLIST = Y(self => list => 
  IF (IS_NIL(list))
    (() => ZERO) 
    (() => ADD(HEAD(list))(self(TAIL(list)))));

console.log( toInt(SUMLIST(list3)) );

const toArray = (list, elementConverter = (x => x)) => {
  const result = [];
  let current = list;

  // While IS_NIL is FALSE (using toInt to bridge the Church Boolean to JS)
  while (toInt(IS_NIL(current)) === 0) {
    // 1. Get the data from the current node
    const churchValue = HEAD(current);
    
    // 2. Convert and push to our JS array
    result.push(elementConverter(churchValue));
    
    // 3. Move to the next node
    current = TAIL(current);
  }
  
  return result;
};

console.log( toArray( list3, toInt ) ); // [3,2,1]

// --- map
const MAP = Y(self => f => list =>
  IF (IS_NIL(list))
    (() => NIL)
    (() => LIST_NODE(f(HEAD(list)))(self(f)(TAIL(list)))));

// Example: Double every number in the list
const DOUBLE = n => ADD(n)(n);
const doubledList = MAP(DOUBLE)(list3); // [6, 4, 2]

console.log("First item doubled:", toInt(HEAD(doubledList))); // 6
console.log("Total:", toInt(SUMLIST(doubledList))); // 6

const LEQ = m => n => IS_ZERO(SUB(m)(n));  // no negative numbers, subtracting from ZERO stays at ZERO!
const GT = m => n => NOT(LEQ(m)(n));
const LT = m => n => NOT(LEQ(n)(m));

console.log( toBool( LEQ(TWO)(FOUR)) ); // true
console.log( toBool( LEQ(FOUR)(TWO)) ); // false
console.log( toBool( LEQ(TWO)(TWO)) );  // true
console.log( toBool( LT(TWO)(FOUR)));   // true
console.log( toBool( LT(FOUR)(TWO)));   // false
console.log( toBool( LT(FOUR)(TWO)) );  // false

Happy coding!

Functional programming in JavaScript (8)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

We continue the previous post on Church encoding. Please make sure you follow by quickly reading the basics.

So let's encode natural numbers. The idea here is to apply a function n-times to encode a natural number n. An auxiliray function to visualise numbers is exacly like "apply i => i+1 to 0 n times". Note how unusual this encoding is - numbers are not just "values", they are "processes". THREE is not just 3, it's a function applied 3 times.

const ZERO  = f => x => x;
const ONE   = f => x => f(x);
const TWO   = f => x => f(f(x));
const THREE = f => x => f(f(f(x)));

const toInt = n => n(i => i + 1)(0);

console.log( toInt( ZERO ) );
console.log( toInt( ONE ) );
console.log( toInt( TWO ) );
console.log( toInt( THREE ) );

ZERO, ONE, TWO, THREE, great but how do we continue? How to define a SUCC function that just computes n+1 from given n? That should be easy: "apply a function n times and just once again":

const SUCC  = n => f => x => f(n(f)(x));

const FOUR = SUCC(THREE);
console.log( toInt( FOUR ) );

Since this could be tricky here, how the SUCC actually work, let's try to symbolically perform some example computations. Everytime you feel unsafe later on, you can verify presented definitions in a similar way.

Let's check what's SUCC(ZERO).

SUCC is n => f => x => f(n(f)(x))

Here, n looks like a function since it's used in a term n(f). And indeed, since ZERO is f => x => x, we have:

SUCC(ZERO) = (n => f => x => f(n(f)(x))(f => x => x)

There seem to be a variable name collision and to avoid it, we rename variables in f => x => x to a => b => b (or anything else not containing n, f and x)

SUCC(ZERO) = (n => f => x => f(n(f)(x))(a => b => b) = (we substitute a => b => b for n) = ...

          ... = f => x => f( (a => b => b)(f)(x) ) = f => x => f( (b => b)(x) ) = f => x => f(x) = ONE

How do we define ADD and MUL? Well, ADD is "apply function n times and then m times". MUL is "apply n times (apply m times)".

const ADD   = m => n => f => x => m(f)(n(f)(x));
const MUL   = m => n => f => m(n(f));

console.log( toInt( ADD(TWO)(THREE) ) );
console.log( toInt( MUL(TWO)(THREE) ) );

That's impressive! POW is even simpler, we just apply m to n:

const POW = m => n => n(m);

console.log( toInt( POW(TWO)(FOUR) ) );

and if this one bothers you as too similar to MUL, you can rewrite it to make it explicit:

const POW = m => n => f => n(m)(f);

console.log( toInt( POW(TWO)(FOUR) ) );

Slow down and carefully consult the difference between MUL and POW.

Ready to continue? In the next post we'll define SUB and write our first complex function.

Tuesday, December 30, 2025

Functional programming in JavaScript (6)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

State management is one of fundamental topics. Consider a state:

let state = { 
  user: { 
    age: 35,
    address: { 
      city: 'Warsaw' } 
    } 
  };

When state changes, an usual way of modifying it would be to just overwrite a part of it:

state.user.address.city = 'Prague';

In the functional world, updating an object is considered a bad practice. Instead, in a functional approach the state would be immutable which means that instead of a local modification, a new state is created. There are good reasons for that:

  • a complete new state means that there is no chance of race condition issues in a concurrent environment
  • a state change history can be tracked which allows so called time travel debugging

Because of this, it is common to encourage immutable states and if you ever studied/used React, you certainly saw something like:

function reducer(state, action) {
  switch (action.type) {
    case 'incremented_age':
      return { ...state, user: { ...state.user, age: state.user.age + 1 } };
    case 'changed_city':
      return { ...state, user: { ...state.user, address: { city: action.new_name } } };
    default:
      throw Error('Unknown action: ' + action.type);
  }
}

console.log( JSON.stringify( state ) );
state = reducer(state, { type: 'changed_city', new_name: 'Prague' } );
console.log( JSON.stringify( state ) );

Note how inconvenient is to create a new state when a deeply nested property is modified. The JavaScript's spread operator (...) helps a bit but still, imagine having dozens of such statemens in your code where modified props are deep down in the state. People often call this the Spread Operator Hell.

A functional approach to this problem, where a new state is to be created from existing state in an atomic way, are Lenses. A Lens lets us have a functional getter and setter (for a property, for an index of an array) and focuses on just a tiny portion of a possibly huge data. A Lens has two operations:

  • view - gets the value the lens focuses on
  • over - applies a given function to the value the lens focuses on
const lens = (getter, setter) => ({
  view: (obj) => getter(obj),
  over: (fn, obj) => setter(fn(getter(obj)), obj)
});

Simple? To view a value, you use the getter. To modify, you use the gettter to get the value, apply a function over it (that's why it's called over) and use setter to set the value back.

We can define our first lens, the Prop lens or Prop-based lens as it takes a property name of an object:

const prop = (key) => lens(
  (obj) => obj[key],                      // The Getter
  (val, obj) => ({ ...obj, [key]: val })  // The Setter (immutable!)
);

Still simple? Should be, JavaScript helps us here as both getting and setting a property of an object, given the property's name, is supported by the language.

And, that's it. Let's see the example. It composes three property lenses into a new lens that focuses on a property deep down in the state:

const userL    = prop('user');
const addressL = prop('address');
const cityL    = prop('city');

// compose them to focus deep into the state
const userCityLens = {
  view: (obj)     => cityL.view(addressL.view(userL.view(obj))),
  over: (fn, obj) => userL.over(u => addressL.over(a => cityL.over(fn, a), u), obj)
};

const currentCity = userCityLens.view(state); 
console.log( currentCity );
state = userCityLens.over(z => 'Prague', state);
console.log( JSON.stringify( state ) );

Take a close look of how the composition is done and make sure you are comfortable with the order of view/over application in the composed lens.

An interesting feature of the lens is that the function can actually operate on the original value (just like an ordinary property setter; lens just does it using a function!) e.g.:

state = userCityLens.over(z => z.toUpperCase(), state);

Still, isn't such manual composition kind of disappointing? Let's see what can be improved here - creating a new lens from existing lenses should be automated!

Well, here it is:

const compose2Lenses = (l1, l2) => ({
  // To view: go through l1, then l2
  view: (obj) => l2.view(l1.view(obj)),  
  // To update: l1.over wraps the result of l2.over
  over: (fn, obj) => l1.over(target => l2.over(fn, target), obj)
});

// A variadic version to compose any number of lenses
const composeLenses = (...lenses) => lenses.reduce(compose2Lenses);

Note how we start by combining just two lenses and then we make a variadic version that just combines an arbitrary number of lenses.

The composed lens can be now defined as:

const userCityLens = composeLenses(userL, addressL, cityL);

Nice! Ready for another step forward? How about replacing the Prop-based lens that takes a property name with another lens, let's call it the Path-based lens (or Selector-based lens) that just takes an arrow function that points to the exact spot in the state object we want to focus on? So we could have:

const userCityLens = selectorLens( s => s.user.address.city );

Compare the two, which one looks better and feels more understandable? I'd prefer the latter. However, to have it, we'd have to somehow parse the given arrow function definition so that the lens is able to learn that it has to follow this path: user -> address -> city. Sounds difficult?

Well, it is. There are two approaches. One would be to stringify the function and parse it to retrieve the path. Another one, preferable, would be to use the JavaScript's Proxy to record the path by just running the function over an object! I really like the latter approach:

const tracePath = (selector) => {
  const path = [];
  const proxy = new Proxy({}, {
    get(_, prop) {
      path.push(prop);
      return proxy; 
    }
  });
  selector(proxy);
  return path;
};

const setterFromPath = (path, fn, obj) => {
  if (path.length === 0) return fn(obj);
  const [head, ...tail] = path;
  return {
    ...obj,
    [head]: setterFromPath(tail, fn, obj[head])
  };
};

const selectorLens = (selector) => {
  const path = tracePath(selector);
  return {
    view: (obj) => selector(obj),
    over: (fn, obj) => setterFromPath(path, fn, obj)
  };
};

A bit of explanation.

First, the tracePath is supposed to get a function and execute it over an empty object. Assuming the function is an arrow function like s => s.user.address.city, the getter will be called 3 times and the path ['user', 'address', 'city'] would be recorded.

Second, the setterFromPath is just a recursive way of applying a function over a path to a given object.

And last, the lens just uses the two auxiliary functions to define view and over.

And how it's used? Take a look:

const userCityLens = selectorLens( s => s.user.address.city );

const currentCity = userCityLens.view(state);
console.log( currentCity );
state = userCityLens.over(z => "Prague", state);
console.log( JSON.stringify( state ) );

And yes, it works! That ends the example.

There are other interesting lenses, like the Prism which handles the case of possible non-existence of the data, in a way similar to the Maybe monad. It's similar to the conditional getter built into the language:

const city = state?.user?.address?.city;

but the interesting thing about the Prism is that it handles both the getter and the setter, while the built-in ?. operator cannot be used at left side of the assignment.

Friday, December 19, 2025

Functional programming in JavaScript (5)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

Another interesting technique that is commonly used in functional programming is the Trampoline. Is a hybrid way of avoiding stack overflows that possibly occur during deep recursive computations.

Functional environments that support Tail Call Optimizations can possibly go deep into recursion. But in V8's JavaScript, stack depth is limited by memory. Since each stack frame consumes a portion of this memory and the stack memory limit is around 1M, depending on how many actual arguments your stack calls have, you can possibly execute about 10000 simple recursive calls. In case of heavy calls (with multiple arguments), this goes down quickly.

Consider this example:

function naiveFac(n) {
  return n <= 1 ? 1 : n * naiveFac(n - 1);
}
console.log( naiveFac(5) );
console.log( naiveFac(10000) );

On my current V8 (node 24), the former computes 120 correctly, the latter throws:

Uncaught RangeError RangeError: Maximum call stack size exceeded
    at naiveFac (c:\Temp\app.js:2:3)

And this is where the Trampoline can be used.

But first, let's refactor this to the Accumulator Passing Style we've already covered:

function naiveFac2(n) {
   return (function factStep(n, accumulator = 1) {
      return n <= 1
         ? accumulator
         : factStep(n-1, n*accumulator);
      })(n);
}
console.log( naiveFac2(5) );
console.log( naiveFac2(10000) );

It still fails for 10000 but the important refactorization is already there.

Now, consider the Trampoline:

function trampoline(fn) {
  while (typeof fn === 'function') {
    fn = fn();
  }
  return fn;
}

First, note that it's imperative, it uses while. And yes, it's not pure, not quite functional but it does the job in a hybrid world of JavaScript. Then, note what it does. It gets a function, executes it and if the return value of the function is another function, it executes it again. And again, until something else than a function is returned. Do you get the idea? Our recursive function, instead just calling itself, will now return a function that calls it but the Trampoline will execute this new function. It avoids recursion but also requires this specific approach that involves the accumulator.

We can now go back to the original issue and refactor it to use the Trampoline:


function trampolineFac(n) {
   function factStep(n, accumulator = 1n) {
      return n <= 1n 
        ? accumulator
        : () => factStep(n-1n, n*accumulator);
   }
   return trampoline( () => factStep(BigInt(n)) );
}

console.log(trampolineFac(5));  
console.log(trampolineFac(10000)); 

Note that it requires some subtle tweaks to actually support BigInts as the result is a huge number. But, hey, it works! The recursion limit is gone!

Friday, December 12, 2025

Functional programming in Javascript (4)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

Monad is one of the most interesting patterns in functional programming. In short, it allows to operate on values that have an extra information attached.

There are various monads and technically, a specific monad is conceptually similar to a class (from object languages). Instances of the monad wrap values, a monad instance contains the wrapped value and an extra state.

A generic monad definition says that you need:

  • a type constructor – that creates a monad type M from some value type A. JavaScript doesn't really care as there are no types at compile time.
  • a return function – that packs/wraps a value into the monad: a → (M a)
  • a bind function – that takes a monad instance, a monadic operation on a pure value and executes this operation and returns a new monad instance: (M a) → (a -> M b) → (M b)

In some programming languages, monads have their own syntactic sugar. For example, in Haskell, the bind is represented by >>= operator.

Our JavaScript example is the Maybe monad. Instead of just saying what problem it solves, let's see the problem.

Let's take a function that takes a string. We want to parse it to convert it to a number and reverse the number. There are two possible points of failure: the string can possibly not represent a number (parsing fails) and the number can possibly be 0 (reversing fails). In a typical imperative/object language, there are two patterns of handling such failures:

  • nested ifs
  • exception handing

The first approach is the least elegant, each possible point of failure requires an extra condition which causes the code to form a pyramid:

function process(input) {

    const value = Number(input);

    if ( !isNaN(value ) ) {
        if ( value != 0 ) {
            const reciprocal = 1 / value;
            return reciprocal;
        }
    }

    return null;
}

console.log( process("not-a-number") );
console.log( process("0") );
console.log( process("2") );

The other approach - a global exception handler - is much cleaner as each possible failure is caught by the very same exception handler:

function process(input) {
    try {
        const value = Number(input);
        const reciprocal = 1 / value;

        return reciprocal;
    }
    catch {
        return null;
    }
}

console.log( process("not-a-number") );
console.log( process("0") );
console.log( process("2") );

The Maybe Monad is a functional alternative to such global exception handling section. At each possible failure point we will have a Maybe instance that will either contain a non-empty value or an empty value and checking the non-emptiness will either be performed in each consecutive step or inside the bind (which will skip a step in case of empty value).

If you come from imperative/object languages that support Nullable wrappers over values (yes, C#, it's about you!) then yes, Maybe instance is really similar to Nullable instance. What is the extra feature here is bind that will allow us to avoid the Pyramid of Doom.

But, we'll have to put some effort into that first.

Let's start with Monad class:

class Maybe {
  constructor(value) {
    this.value = value;
  }

  bind(f) {
    if (this.value === null || this.value === undefined) {
      return Maybe.Nothing();
    }
    return f(this.value);
  }

  static of(value) {
    return new Maybe(value);
  }

  static Nothing() {
    return new Maybe(null);
  }
}

Note how simple it is. The bind is here, the return is here, too (it's called of) and we even have an extra constructor for the empty value (Nothing).

We are ready to implement the two monadic operations. Go back to the very start and consult the signature of bind - monadic operations are functions that take pure values and return monad instances:

// parsing
function parse(str) {
  const n = Number(str);
  return isNaN(n) ? Maybe.Nothing() : Maybe.of(n);
}

// reversing
function recp(n) {
  return n === 0 ? Maybe.Nothing() : Maybe.of(1 / n);
}

And ... that's it!

Oh, really?

Yes! We can already write monadic code:

function process1( i ) {
  return Maybe.of(i) // wrap input
    .bind(input => 
      parse(input) // parse
        .bind(number => 
          recp(number) // reverse
            .bind(reciprocal => 
              Maybe.of(reciprocal) // wrap output
            )
        )
    );
}

console.log( process1( null ) );
console.log( process1( "0" ) );
console.log( process1( "2" ) );

Note that there's no single if in the code because ifs are hidden inside monadic operations and inside bind!

But wait! It's disappointing! The Pyramid of Doom is still there!

How other functional languages tackle this? Take a look at Haskell, a raw bind has the same problem, you need to pass an arrow function as an argument to bind and each consecutive monadic operation is a new arrow function next to the previous one:

  getLine >>= \name -> putStrLn ("Hello, " ++ name ++ "!")

The first possible step into right direction would be - since bind returns a monad instance - to flatten the code:

function process1(i) {
  return Maybe.of(i) // wrap input
    .bind(input =>
      parse(input))  // parse
    .bind(number =>
      recp(number))  // reverse 
    .bind(reciprocal =>
      Maybe.of(reciprocal) // wrap output
    );
}

That looks much better, the pyramid is gone. But it has a serious drawback. In the previous approach, each intermediate result (input, number, reciprocal) was caught by a closure and was available in the very next nested arrow function. All three are available at the end.

In this new, flatten version, this feature is gone. No closures, each bind is side-by-side with other binds and has only its own value. To be able to pass all intermediate values down the pipeline, we'd have to wrap them in arrays and return monadic instances that wrap two, three raw values. That doesn't sound right.

How Haskell solves this? They have the syntactic sugar called the do notation which is basically a special block of code where monadic instances can be unwrapped into temporary variables using the <- operator.

main = do
  name <- getLine
  putStrLn ("Hello, " ++ name ++ "!")

And yes, this is the ultimate syntax. The do notation is the crucial element of the language that makes monads feel natural in the language. It's so important that other functional languages have it, OCaml has the let*, Scala has for { } blocks!

Can we have it in JavaScript? Well, we can't add our own syntactic sugar into the language. But we can have a function!

Let's face it. It's not obvious. Monadic operations return monad instances and it's bind that unwraps monad instances into raw values. Such do-like function should allow us to unpack monads and also, keep all unpacked values in a single closure-like "scope" so that all of them are available after obtained.

One of the very beautiful ways to do this involve using JavaScript's generators! We will write the do-block as a generator function and we will unpack monad instances using yield! JavaScript is unique - yield is a two way operator. It not only returns a value to the caller but also lets the caller to push a value back to the generator so that yield can be used at the right side of the assignment operator! No other language that has yield support this two-way communication!

JavaScript's do is surprisingly short then but very clever. We call it doM as do is a reserved keywork in the language:

function doM(gen) {
  function step(value) {
    const result = gen.next(value);
    if (result.done) return result.value;
    return result.value.bind(step);
  }
  return step();
}

A side note: this function uses this highly unique feature of JavaScript that allows us to call gen.next(value) to push values into the generator. You can study this contrived example:

// generator returns 1,2,3 to the client
function* gen() {
    var a = yield 1;
    console.log( `a = ${a}` );
    var b = yield 2;
    console.log( `b = ${b}` );
    var c = yield 3;
    console.log( `c = ${c}` );
}

var it = gen();
var i = 0;
var a = [null, 17, 18, 19];
// the client pushes 17, 18, 19 back into the generator
while (true) {
  const { value, done } = it.next(a[i++]);
  if (done) break;
  console.log(value);
}

Back from the side note, with doM monadic code can be refactored to clean, linear code where there's no bind at all and monadic operations appear on the right sides of the yield operator but they yield raw values on left sides of assignments. And since a generator is a function, all raw values are available in it after they are assigned!

function process2( i ) {
    return doM(
        function* () {
            const input      = yield Maybe.of(i); 
            const number     = yield parse(input);
            const reciprocal = yield recp(number);

            return Maybe.of(reciprocal);
        }()
    );
};

console.log( process2( null ) );
console.log( process2( "0" ) );
console.log( process2( "2" ) );

Holly molly, that's nice! There's no try-catch but it feels like one, whenever an operation fails, a monad with empty value is passed down the pipeline and bind just skips over it!

There's one almost-monad built into JavaScript - it's the Promise monad, the one that allows async operations. It has its own syntax, no do block and no generator with yield but there's async as a function decorator and await for unpacking raw values.

async function process3( i ) {
   const input      = await Promise.resolve(i); 
   const number     = await parseAsync(input);
   const reciprocal = await recpAsync(number);
   
   return Promise.resolve(reciprocal);
};

Note that async-await is not about exception handling, it's about handling async operations. If you just thought that there could be other interesting monads that solve other issues but also benefit from this kind of do-notation syntax then yes, functional languages like OCaml and Scala have other monads and Haskell features so called monad transformers where you combine different monads in one do block!

Monad Promise
Maybe.of Promise.resolve
bind then
do function async decorator
yield inside the do block await in an async function

What we just demonstrated, though, is that we can have similar feature, built in a functional way. And yes, async/await is internally implemented very similarily to yield generators. Before async/await syntactic sugar was introduced, people were coding their own async monads using the pattern we've just demonstrated, using yield and an auxiliary do-like function. These early attempts can still be found, take a look at the co library for example.

Happy coding!

Functional programming in JavaScript (3)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

Functional programming is also about recursion. Take a simple factorial:

const fac = n => n > 1 ? n * fac(n-1) : 1

console.log( fac(5) );

That looks super easy but what if you want to write a recursive function without using a recursive function name in its definition?

In the above example, this would mean you can bind a function to a variable fac but you can't use the name fac in the function definition.

Not possible?

Consider this, then:

const fac = 
  (f => n => n > 1 ? n * f(f)(n-1) : 1)
  (f => n => n > 1 ? n * f(f)(n-1) : 1);

console.log( fac(5) );

which technically means that you don't even need to bind it to a separate name (fac):

console.log(
  (f => n => n > 1 ? n * f(f)(n-1) : 1)
  (f => n => n > 1 ? n * f(f)(n-1) : 1)
  (5)
)

Hold on, most of us need time to comprehend this. Let's examine.

The core definition of the function:

n => n > 1 ? n * fac(n-1) : 1

just got a new level of abstraction:

f => n => n > 1 ? n * f(n-1) : 1

but to actually be able to piggyback the function onto itself, we need to pass it to itself as f and in the same time, pass the passed function to itself in every call, f(f):

  (f => n => n > 1 ? n * f(f)(n-1) : 1)
  (f => n => n > 1 ? n * f(f)(n-1) : 1)

This is clever and one could ask: what if I don't want to repeat the definition twice so that I can pass it to itself?

This is doable but with an auxiliary helper called the Y combinator.

Consider this:

const Y = f => (x => f(y => x(x)(y)))(x => f(y => x(x)(y)));

const fac = Y(f => n => n > 1 ? n * f(n-1) : 1);

This auxiliary helper function, called Y, basically wraps this passing-a-function-to-itself. Note that its core body

x => f(y => x(x)(y))

is indeed repeated twice. This higher order function, Y, is now a factory of functions and can make any function recursive, the recursive call is resolved not by-name but by-binding: in our example, Y is applied to:

f => n => n > 1 ? n * f(n-1) : 1

and note that f binds the supposed recursive function name here.

And, because this core body is repeated twice, Y can be refactored to:

const Y = f => (x => x(x))(x => f(y => x(x)(y)));

const fac = Y(f => n => n > 1 ? n * f(n-1) : 1);

And that's it. The Y is undeniably an impressive idea.

Thursday, December 11, 2025

Functional programming in JavaScript (2)

Please take a look at other posts about functional programming in JavaScript:

  1. Part 1 - what Functional Programming is about
  2. Part 2 - Functional Pipelines
  3. Part 3 - the Y Combinator
  4. Part 4 - Monads
  5. Part 5 - Trampoline
  6. Part 6 - Lenses
  7. Part 7 - Church encoding (booleans)
  8. Part 8 - Church encoding (arithmetics)
  9. Part 9 - Church encoding (if, recursion)
  10. Part 10 - Church encoding (lists)
  11. Part 11 - Church encoding (strings, objects)
  12. Part 12 - modularity

The pipeline operator is one of features of many functional languages. Take a look at this F# example:

[1; 2; 3; 4;]
|> List.filter (fun x -> x % 2 <> 0)
|> List.map (fun x -> x * x + 1)

What problem this syntax solves?

Think of a typical app. User inputs some data and the app processes the data. There's validation, then some processing, then mapping input to an output.

A usual flow in an imperative/object language, is a sequence of loops (for/while). Each loop does some filtering, ordering, mapping, groupping etc.

var list = [1,2,3,4];
for ( var i=0; i < list.length; i++ )
{
    // validation
    if ( ... ) { ... }
}
for ( var i=0; i < list.length; i++ )
{
    // processing
}
// ...

It's usually hard to follow such code and also not easy to maintain it. Loops can have side effects, the list is modified or maybe it's not, loop indexes have to be carefully inspected to find possible subtle mistakes. When a loop groups data lists into dictionaries, things get even more complicated.

But, if a list has its own programming interface, the code can be refactored to much cleaner:

var result = 
    [1,2,3,4]
        .filter( x => x < 2 ) // validation
        .map( x => x * 2 )    // processing
        ...

This clean syntax is only possible because of existence of these specific methods, filter or map. These methods take a list and return another list which is an argument to the very next method call. The code flow is very clear, arguments are clear.

But what if you want to call a method that is not built into the array interface?

var result = 
    [1,2,3,4]
        .filter( x => x < 2 ) // validation
        .saveToDatabase()     // ?? missing, there's no such method
        ...

In functional approach, such pipeline can be implemented using functions that have exactly one parameter - a list and one return value - a list.

function filterEvens( xs ) {
    return xs.filter( x => x % 2 == 0 );
}
function double( xs ) {
    return xs.map( x => x*2);
}

console.log(
    double(
        filterEvens(
            [1,2,3,4,5]
        )
    )
)

This is a step in a right direction. It no longer relies on built-in methods, instead, custom functions can be easily implemented. The saveToDatabase would be just another function that takes a list and returns a list (so that in can be chained further).

The problem here is that the syntax is unfortunate. The actual argument (the data) is in the middle of a possibly long sequence of calls and functions that are applied to the data are written bottom-to-top instead of top-to-bottom. In the above example, what we see is double followed by filterEvens while in fact it's first filterEvens that is applied, followed by double. Such code where the argument is in the very center (or at the top, just tilt your head to the right) is called a Pyramid of Doom and it's a problem not only in JavaScript.

Let's try to fix that by introducing the pipeline operator, just like F#'s |>. It's the operator that makes the code clean and functions applied in the very same order they appear in the code.

In JavaScript, we can't override a custom operator. You just can't have the |>. But, we can have a function that does the same.:

  
function pipe(xs, ...[f, ...fs]) {
    return f ? pipe( f(xs), ...fs ) : xs;
}

This pipe function is really simple. It takes a list (xs) and a list of functions (using the spread operator). It uses recursion to apply a next function to return value of previous function. Calling:

pipe( xs, f1, f2, f3 )

would yield:

f3( f2( f1( xs )))

Make sure it really does so! Using this simple function, we can rewrite the previous pipeline to:

console.log( 
    pipe( 
        [1,2,3,4,5],
            filterEvens,
            double
    )
);

Another step in the right direction. No, we still don't have the |> but we have the pipe function that does the same.

But - do we really need an extra function in the pipeline for every possible operation we would like to perform? In the example, to filter even numbers we have a function. Does it mean that any other filtering, like odd numbers or persons that are older than 18 years or orders that are ready to be shipped, would require its own extra function?

No, we can generalize that!

How do we generalize a function - like a filtering function - so that it takes just one parameter (a list) but in the very same time, another parameter, the filtering predicate?

Just make a function with two parameters?

Nope, we need exactly one!

Well, technically yes and no. We can have a higher order function. A function that takes parameters but returns another function with its own parameters. A function that creates functions. A function factory.

function map( f ) {
    return function( xs ) {
        return xs.map( f );
    }
}

function filter( predicate ) {
    return function( xs ) {
        return xs.filter( predicate );
    }
}

function sort( compareFn ) {
    return function( xs ) {
        return xs.sort( compareFn );
    }
}

function reduce( foldf ) {
    return function( xs ) {
        return xs.reduce( foldf );
    }
}

function flat() {
    return function( xs ) {
        return xs.flat();
    }
}

function take(n) {
    return function( xs ) {
        return xs.slice(0, n);
    }
}

console.log( 
    pipe( 
        [1,2,3,4,5],
            map( n => n + 1 ),
            filter( x => x < 4 ),
            map( n => n.toString() ),
            map( n => [n, n] ),
            flat(),
            sort( (n,m) => n-m ),
            map( n => +n ),
            reduce( (prev, curr) => prev + curr )
    )
);

With this approach, creating new pipeline operators is easy. And, compare this syntax to the F# example from the very beginning of this post.

To make it even more fun, all these pipeline operators that actually kind of wrap existing array methods can be also generalized using yet another level of abstraction:

function curryArrayMethod(method) {
  return function curried(func) {
    return function(array) {
      return method.call(array, func);
    };
  };
}

const curriedFilter = curryArrayMethod(Array.prototype.filter);
const curriedMap    = curryArrayMethod(Array.prototype.map);

console.log( 
    pipe( 
        [1,2,3,4,5],
        curriedFilter( x => x < 4 ),
        curriedMap( x => x * 2 )
    )
);

Have fun with functional pipelines in JavaScript.

As an excercise, you can add your own operator (like the group operator) or modify the sort operator so that instead of a comparer:

  ...
  sort( (n,m) => n-m )

it takes a function that gets the sort key of a single value and internally uses this function to compare two values, so that you can call sort like:

...
  sort( person => person.name )

Monday, April 15, 2024

Rust/WebAssembly vs Javascript performance ... reloaded

Last year I've blogged about a tiny contest where Rust/WASM and Javascript were used to implement a simple Mandelbrot animation. I've polished the code, put it in a github repo, the rust-vs-js. I've also added a third contestant, the gpu.js accelerated version, which of course beats the heck out of the two (Javascript and Rust) since it's heavily parallelized.
Anyway, jump to the repository and enjoy the code.

Monday, August 28, 2023

Rust/WebAssembly vs Javascript performance on Mandelbrot animation rendering

The pending question Is Rust/Wasm fast enough to even bother when comparing to Javascript? has now yet another biased benchmark. I've decided to take one of my Julia/Mandelbrot demos, benchmark it "as-is" and then, port to Rust and compare.
The HTML/Javascript source is short enough to post it here, the original demo code has some additional features (zooming) which are not present here
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mandelbrot</title>
	<script type="text/javascript">
	        
        var cx = 0, cy = 0, kat1 = 0, kat2 = 1;           
        
        var WJulia = 1024;
        var HJulia = 1024;
        var frame  = 0;
        var startDate;
    
        var contextJulia;
        var contextSmall;
        var pixJulia;
        var imgdJulia;

        var iStart;
        var iEnd;
        var jStart;
        var jEnd;

        var iDelta;
        var jDelta;
        
        function setInitialScale()
        {
            iStart = -1.92;
            iEnd   = 1.92;
            jStart = -1.92;
            jEnd   = 1.92;

            iDelta = (iEnd-iStart)/1024;
            jDelta = (jEnd-jStart)/1024;

            startDate = new Date();
        }

        function SetupMandel()
        {	 
            var elemJulia = document.getElementById('JuliaCanvas');
            if (elemJulia && elemJulia.getContext)
            {
                contextJulia = elemJulia.getContext('2d');
                if (contextJulia)
                {
                    imgdJulia = contextJulia.createImageData(WJulia, HJulia);         
                    pixJulia = imgdJulia.data;
                }
            }

            setInitialScale();
          
            /* start */
            requestAnimationFrame( LoopMandel );
        }
                         
        function LoopMandel()
        {	 
            kat1 += 0.0021;
            kat2 += 0.0039;
            cx = .681 * Math.sin(kat1);
            cy = .626 * Math.cos(kat2);

            frame++;
            document.getElementById('fps').innerHTML = `FPS: ${1000*frame/(new Date()-startDate)}`;
			
            RysujMandel();	 
            
            requestAnimationFrame( LoopMandel );
        }
         
         
        /* tworzenie bitowego obrazu */
        function RysujMandel()
        {
            /* obliczenia */
            var wi, wj;
            var i, j;

            var iterations = 255;

            var px = 0;
            for (i = iStart, wi = 0; wi < 1024; i += iDelta, wi++)
            {
                var py = 0;
                for (j = jStart, wj = 0; wj < 1024; j += jDelta, wj++)
                {
                    var c = 0;

                    var x = cx;
                    var y = cy;
         
                    while (((x*x + y*y) < 4) && (c < iterations))
                    {
                        [x, y] = [x * x - y * y + i, 2 * x * y + j];
                        c++;
                    }

                    SetPixelColor( pixJulia, (py * WJulia + px) << 2, 255, 255-c, 255-c, 255 - (c/2) );
                                        
                    py++;
                }
         
                px++;
            }
            
            /* kopiowanie bitowego obrazu do context/canvas */
            contextJulia.putImageData(imgdJulia, 0, 0);		 
        }
         
        function SetPixelColor(pix,offs, a, r, g, b)
        {            
            pix[offs++] = r;
            pix[offs++] = g;
            pix[offs++] = b;
            pix[offs] = a;
        }
         
        window.addEventListener( 'load', SetupMandel );
        
        </script>    
</head>
<body>
    <span id="fps" style='display:block'></span>
    <canvas id="JuliaCanvas" width="1024" height="1024">
	</canvas>
</body>
</html>
When run on my machine and the Edge Browser, it makes ~10-11 frames per second. Not bad assuming 1024x1024 image and 255 iterations.
Same code ported to Rust and compiled with wasm-pack
// https://rustwasm.github.io/wasm-bindgen/examples/dom.html
use wasm_bindgen::prelude::*;
use wasm_bindgen::Clamped;
use web_sys::{CanvasRenderingContext2d, ImageData};

/* tworzenie bitowego obrazu */
#[wasm_bindgen]
pub fn mandel(
    ctx: &CanvasRenderingContext2d, 
    width: u32, height: u32,
    cx: f64, cy: f64) -> Result<(), JsValue> {

    let i_start = -1.92;
    let i_end   = 1.92;
    let j_start = -1.92;
    let j_end   = 1.92;

    let i_delta = (i_end-i_start)/width as f64;
    let j_delta = (j_end-j_start)/height as f64;

    /* obliczenia */    
    let iterations = 255;

    let mut pix_julia = Vec::with_capacity( usize::try_from(width * height).unwrap() );

    let mut j = j_start;
    for _wj in 0..height {

        let mut i = i_start;   
        for _wi in 0..width {
        
            let mut c: u8 = 0;

            let mut x = cx;
            let mut y = cy;
    
            while ( (x*x + y*y) < 4.0) && (c < iterations)
            {
                let _tx = x;
                x = x * x - y * y + i;
                y = 2.0 * _tx * y + j;
                c += 1;
            }

            pix_julia.push( 255-c );
            pix_julia.push( 255-c );
            pix_julia.push( 255-(c/2) );
            pix_julia.push( 255 );
            
            i  += i_delta;
        }
    
        j  += j_delta;
    }    

    let data = ImageData::new_with_u8_clamped_array_and_sh(Clamped(&pix_julia), width, height)?;
    ctx.put_image_data(&data, 0.0, 0.0)
}
The cargo.tomlwas
[package]
name = "hello-wasm"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2.87"

[dependencies.web-sys]
version = "0.3.4"
features = [
  'Document',
  'Element',
  'HtmlElement',
  'Node',
  'Window',
  'ImageData',
  'CanvasRenderingContext2d'  
]

[profile.release]
opt-level = 3
lto = true

[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-O4", "--enable-mutable-globals"]
and the HTML
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Mandelbrot</title>
  </head>
  <body>
    <script type="module">
        import init, { mandel } from "./pkg/hello_wasm.js";
        
        (async function() {
		   await init();
           SetupMandel();    
        })();
	  
        var cx = 0, cy = 0, kat1 = 0, kat2 = 1;      
        var WJulia = 1024;
        var HJulia = 1024;        
        var frame  = 0;
		var startDate;
        
        var contextJulia;
        var contextSmall;
        var pixJulia;
        var imgdJulia;

        function SetupMandel()
        {	 
            var elemJulia = document.getElementById('JuliaCanvas');
            if (elemJulia && elemJulia.getContext)
            {
                contextJulia = elemJulia.getContext('2d');
                if (contextJulia)
                {
                    imgdJulia = contextJulia.createImageData(WJulia, HJulia);         
                    pixJulia = imgdJulia.data;
                }
            }
          
		    startDate = new Date();
			
            /* start */
            requestAnimationFrame( LoopMandel );
        }
                         
        function LoopMandel()
        {	 
            kat1 += 0.0021;
            kat2 += 0.0039;
            cx = .681 * Math.sin(kat1);
            cy = .626 * Math.cos(kat2);

            frame++;
            document.getElementById('fps').innerHTML = `FPS: ${1000*frame/(new Date()-startDate)}`;
			
            mandel(contextJulia, WJulia, HJulia, cx, cy);	 
            
            requestAnimationFrame( LoopMandel );
        }	  
    </script>
    <span id="fps" style='display: block'></span>	
    <canvas id="JuliaCanvas" width="1024" height="1024">
	</canvas>	
  </body>
</html>
And the result? Similar, it also makes 10-11 frames per second. Additional tests (different resolution and number of iterations) and possible optimizations can be applied here.

Friday, October 1, 2021

tiny-totp.js, a tiny TOTP javascript implementation

Just published the tiny-totp.js code on Github. It's super tiny Javascript RFC6328 implementation. If you wonder what's that, it's the Timed One-Time Passwords specs that is widely used to implement two-factor authentication over web.

What this tiny library does is it computes one time passwords, given the master password. It's basically the same computation Google Authenticator or Microsoft Authenticator do, given the master password. It means that you can either implement your own client or even your own server side authentication that would be compatible with existing authenticators (including the two).

What's interesting here is that the implementation is really, really tiny and has 0 dependencies. Usually, people implement TOTP using two dependencies:

  • to handle the base32 encoding (master keys are usually provided in base32 encoding
  • to handle the hmacsha1 to calculate actual codes
This code avoids both dependencies - there's a tiny function to handle base32 and platform specific crypto provider is used to handle hmacsha1 (the node's crypto module when run against node or window.subtlecrypto when run in a browser).

Tuesday, October 27, 2020

Materiały edukacyjne - funkcje w Javascript

Czwarty wykład z Wybranych elementów praktyki projektowania oprogramowania, o programowaniu funkcyjnym w Javascript, to jeden z moich ulubionych, łącznie z kolejnym o obiektowości prototypowej. Tu opowiadam o tym jak w Javascript zobaczyć język funkcyjny, z takimi elementami funkcyjnymi jak funkcje wyższych rzędów, rekursja, domknięcia, kontynuacje. Zrozumienie tych elementów języka znacznie ułatwia swobodne poruszanie się w bibliotekach UI, takich jak React (komponenty funkcyjne).
Zapraszam do oglądania.

Thursday, May 9, 2019

Tetris challenge - reloaded (Javascript)

Years ago I've blogged on a challenge which was to implement a simple tetris game. This new reloaded version is a direct one-to-one translation to vanilla Javascript and runs in a browser. Feel free to learn from the code and/or reuse it in any way. Note that the UP key has to be pressed to start the game.
(Re)start: up
Moves: left/right/down/space
The code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>

        var pieceMove = {
            left:   'left',
            right:  'right',
            up:     'up',
            down:   'down',
            rotate: 'rotate'
        };
    
        function board() {
            this.MARGIN      = 5;
            this.SIZEX       = 10;
            this.SIZEY       = 40;
            this.BLOCKSIZE   = 10;
            this.PIECESTARTX = 8;
    
            var i, j;
    
            this.squares = new Array( this.MARGIN + this.SIZEX + this.MARGIN );
            for ( i=0; i < this.squares.length; i++ )
                this.squares[i] = new Array( this.MARGIN + this.SIZEY + this.MARGIN );
    
            // fill the margin 
            for ( i=0; i < this.MARGIN + this.SIZEX + this.MARGIN; i++ )
                for ( j=0; j < this.MARGIN; j++ )
                    this.squares[i][j] = this.squares[i][j + this.SIZEY + this.MARGIN] = true;
            for ( i=0; i < this.MARGIN; i++ )
                for ( j=0; j < this.MARGIN + this.SIZEY + this.MARGIN; j++ )
                    this.squares[i][j] = this.squares[i + this.SIZEX + this.MARGIN][j] = true;        
    
            this.currentPiece  = piece.getRandomPiece();
            this.currentPieceX = this.PIECESTARTX;
            this.currentPieceY = this.MARGIN;        
    
            this.score         = 0;
        }
    
        board.prototype.obtainContext = function(canvas) {
            this.context       = canvas.getContext('2d');     
            this.contextWidth  = canvas.width;
            this.contextHeight = canvas.height;       
        }
    
        board.prototype.paint = function() {
            
            var i, j;
    
            this.context.fillStyle = 'white';
            this.context.fillRect(0, 0, this.contextWidth, this.contextHeight);
    
            // background
            this.context.fillStyle = 'black';
    
            for ( i=0; i < this.SIZEX; i++ )
                for ( j=0; j < this.SIZEY; j++ )
                    if ( this.squares[this.MARGIN + i][this.MARGIN + j] )
                        this.context.fillRect( i * this.BLOCKSIZE, j * this.BLOCKSIZE, this.BLOCKSIZE, this.BLOCKSIZE );
    
            // piece
            if ( this.currentPiece ) {
                for ( i=0; i < this.currentPiece.SIZE; i++ )
                    for ( j=0; j < this.currentPiece.SIZE; j++ )
                        if ( this.currentPiece.blockData[i][j] ) {
                            this.context.fillRect( (this.currentPieceX - this.MARGIN + i) * this.BLOCKSIZE, ( this.currentPieceY - this.MARGIN + j ) * this.BLOCKSIZE, 
                                                    this.BLOCKSIZE, this.BLOCKSIZE);
                        }
            }    

            // score
            this.context.fillStyle = 'red';
            this.context.fillText( this.score, 5, 10 );
        }
    
        /* Advance one step of the game */
        board.prototype.autoUpdate = function() {

            this.removeFullLines();
    
            if ( this.currentPiece ) {
                var _newX = this.currentPieceX;
                var _newY = this.currentPieceY + 1;
    
                if ( this.isLegalPosition( this.currentPiece, _newX, _newY ) ) {
                    this.currentPieceY = _newY;
                }
                else {
                    this.absorbCurrentPiece();
    
                    this.currentPiece  = piece.getRandomPiece();
                    this.currentPieceX = this.PIECESTARTX;
                    this.currentPieceY = this.MARGIN;
    
                    if ( !this.isLegalPosition( this.currentPiece, this.currentPieceX, this.currentPieceY ) ) {
                        this.score = 'Game over: ' + this.score;
                        this.currentPiece = null;

                        return false;
                    }
                }
            }    

            return true;
        }
    
        /* Remove all full lines */
        board.prototype.removeFullLines = function() {
            var fullLineNumber = -1;
            do
            {
                fullLineNumber = this.getPossibleFullLine();
                if ( fullLineNumber >= 0 )
                    this.removeLine( fullLineNumber );
            } while ( fullLineNumber >= 0 );
        }
    
        /* Check if one of lines is possibly filled */
        board.prototype.getPossibleFullLine = function() {
            for ( var j = 0; j < this.SIZEY; j++ )
            {
                var isFull = true;
                for ( var i = 0; i < this.SIZEX; i++ )
                    isFull &= this.squares[this.MARGIN + i][this.MARGIN + j];
    
                if ( isFull )
                    return j + this.MARGIN;
            }
    
            return -1;
        }
    
        /* Remove selected line */
        board.prototype.removeLine = function( lineNumber ) {
            for ( var j = lineNumber; j > this.MARGIN; j-- )
                for ( var i=this.MARGIN; i < this.SIZEX + this.MARGIN; i++ )
                    this.squares[i][j] = this.squares[i][j - 1];
    
            this.score += 1;
        }
    
        /* Copy piece data to board's block data. Called only when piece becomes "solid", non-movable. */
        board.prototype.absorbCurrentPiece = function() {
            if ( this.currentPiece )
                for ( var i=0; i < this.currentPiece.SIZE; i++ )
                    for ( var j=0; j < this.currentPiece.SIZE; j++ )
                        if ( this.currentPiece.blockData[i][j] )
                            this.squares[i + this.currentPieceX][j + this.currentPieceY] = true;
        }
    
        /* Moves current piece into a new position, if possible */
        board.prototype.moveCurrentPiece = function(move) {
    
            var _newPiece = this.currentPiece;
            var _newX     = this.currentPieceX;
            var _newY     = this.currentPieceY;
    
            if ( this.currentPiece )
            {
                if ( move == pieceMove.rotate ) _newPiece = piece.rotate( this.currentPiece );
                if ( move == pieceMove.left )   _newX = this.currentPieceX - 1;
                if ( move == pieceMove.right )  _newX = this.currentPieceX + 1;
                if ( move == pieceMove.down )   _newY = this.currentPieceY + 1;
    
                // move only if legal position
                if ( this.isLegalPosition( _newPiece, _newX, _newY ) )
                {
                    this.currentPiece  = _newPiece;
                    this.currentPieceX = _newX;
                    this.currentPieceY = _newY;
                }
            }
        }
    
        /* Is the new possible position of a piece "legal" in a sense that the piece doesn't overlap with non-empty cells */
        board.prototype.isLegalPosition = function( piece, pieceX, pieceY ) {
            for ( var i=0; i < piece.SIZE; i++ )
                for ( var j=0; j < piece.SIZE; j++ )
                    if ( piece.blockData[i][j] &&
                         this.squares[i + pieceX][j + pieceY]
                        )
                        return false;
    
                return true;
        }
    
        function piece(r0, r1, r2, r3, r4) {
            this.SIZE = 5;
    
            var i;
    
            this.blockData = new Array( this.SIZE );
            for ( i=0; i < this.SIZE; i++ )
                this.blockData[i] = new Array( this.SIZE );
    
            for ( i=0; i<this.SIZE; i++ ) {
                this.blockData[i][0] = r0[i];
                this.blockData[i][1] = r1[i];
                this.blockData[i][2] = r2[i];
                this.blockData[i][3] = r3[i];
                this.blockData[i][4] = r4[i];
            }
        }
    
        piece.rotate = function( source ) {
            if ( source == piece.i_horiz ) return piece.i_vert;
            if ( source == piece.i_vert )  return piece.i_horiz;
    
            if ( source == piece.z_lefthoriz ) return piece.z_leftvert;
            if ( source == piece.z_leftvert )  return piece.z_lefthoriz;
    
            if ( source == piece.z_righthoriz ) return piece.z_rightvert;
            if ( source == piece.z_rightvert )  return piece.z_righthoriz;
    
            if ( source == piece.l_l1 ) return piece.l_l2;
            if ( source == piece.l_l2 ) return piece.l_l3;
            if ( source == piece.l_l3 ) return piece.l_l4;
            if ( source == piece.l_l4 ) return piece.l_l1;
    
            if ( source == piece.r_l1 ) return piece.r_l2;
            if ( source == piece.r_l2 ) return piece.r_l3;
            if ( source == piece.r_l3 ) return piece.r_l4;
            if ( source == piece.r_l4 ) return piece.r_l1;
    
            return piece.box;
        }
    
        piece.getRandomPiece = function() {
            var _next = Math.floor( Math.random() * 6 );
            switch ( _next ) {
                case 1  : return piece.z_lefthoriz;
                case 2  : return piece.z_righthoriz;
                case 3  : return piece.l_l1;
                case 4  : return piece.r_l1;
                case 5  : return piece.i_horiz;
                default : return piece.box;
            }
        }
    
        piece.box = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.i_horiz = new piece(
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.i_vert = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 1, 1, 1, 1 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.z_lefthoriz = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 0, 1, 1, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.z_leftvert = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 1, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.z_righthoriz = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 1, 1, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.z_rightvert = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 1, 0 ],
            [0, 0, 0, 1, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.l_l1 = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 1, 0, 0, 0 ],
            [0, 1, 1, 1, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.l_l2 = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 1, 0, 0, 0 ],
            [0, 1, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.l_l3 = new piece(
            [0, 0, 0, 0, 0 ],
            [1, 1, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.l_l4 = new piece(
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 1, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.r_l1 = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 1, 0 ],
            [0, 1, 1, 1, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.r_l2 = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 1, 1, 0 ],
            [0, 0, 0, 1, 0 ],
            [0, 0, 0, 1, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.r_l3 = new piece(
            [0, 0, 0, 0, 0 ],
            [0, 0, 1, 1, 1 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
        piece.r_l4 = new piece(
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 0, 0 ],
            [0, 0, 1, 1, 0 ],
            [0, 0, 0, 0, 0 ],
            [0, 0, 0, 0, 0 ]        
        );
    
        
        var _board;
    
        var _interval;              // current frame interval
        var _speedinterval = 15000; // speed up every 15 sec

        var _intervalHandle;
    
        /*
            * This advances one frame
            */
        function tick() {
            _board.paint();
            if ( _board.autoUpdate() ) {
                _intervalHandle = setTimeout( tick, _interval);
            }
        }
    
        /*
            * This fires every 15 seconds and decreases the timeout of the other timer
            */
        function speedup() {
            if ( _interval > 20 )
                _interval -= 10;
        }
    
        function init(canvas) {
            _interval      = 200;

            _board = new board();
            _board.obtainContext(canvas);
        
            _intervalHandle = setTimeout( tick, _interval ); 
        }

        (function main(){
                        
            window.addEventListener('load', function() {
                var canvas = document.getElementById('tetris');

                canvas.addEventListener('click', function() {
                    if ( _intervalHandle )
                        clearTimeout( _intervalHandle );
                    init(canvas);
                });
                
                setInterval( speedup, _speedinterval );
            } );
    
            window.addEventListener( 
                'keydown', 
                function(e) {
                    //e.preventDefault();
                    if ( e.keyCode == 37 ) // arrow left
                        _board.moveCurrentPiece( pieceMove.left );
                    if ( e.keyCode == 39 ) // arrow right
                    _board.moveCurrentPiece( pieceMove.right );
                    if ( e.keyCode == 40 ) // arrow down
                        _board.moveCurrentPiece( pieceMove.down );
                    if ( e.keyCode == 32 ) // space
                        _board.moveCurrentPiece( pieceMove.rotate );
    
                    _board.paint();
                }
            );

        })();
    
    </script>
    <style>
        #welcome {
            border: 1px solid black;
            font: 10px tahoma;
            width: 100px;
        }
        #tetris {
            border: 1px solid black;
        }
    </style>    
</head>
<body>

    <div id="welcome">
        Moves: left/right/down/space
        Click: (re)start.
    </div>
    <div>
        <canvas id="tetris" width="100" height="400">
        </canvas>
    </div>

</body>
</html>