Monday, August 3, 2015

JavaScript meet Lisp

I like recursion.

JavaScript arrays are not the greatest when it comes to easily handling recursion. When you are working with them you don't want to mutate them. You also don't want to copy them.

You know what was great for recursion. Singly linked list like in Scheme/Lisp. Nowadays I say stuff like "car" and "cdr" and I get blank stares from my mentees. Simple recursion handled the car and then recursed on the cdr. It was very simple and easy.

Here is a simple object to wrap an array and give Scheme/Lisp like recursion in TypeScript. It is super simple and raw and even potentially dangerous, but used correctly it makes recursive code processing of an array look much nicer.

module HP.DataStructures {    
    export class LispArrayWrapper {
        constructor(private array: any[], 
                    private internalPointer = 0){
        }
        public isEmpty() {
            return this.internalPointer >= this.array.length;
        }
        public car() {
            return this.array[this.internalPointer];
        }
        public cdr() {
            return new LispArrayWrapper(
                this.array,
                this.internalPointer + 1);
        }
    }

}

No comments:

Post a Comment