Skip to content. | Skip to navigation

Personal tools
Log in
Sections
You are here: Home

jorgenmodin.net - Blog

Some languages that compile to javascript

Posted by admin |

Most of these untested by me.

Scala.js Scala.js

Clojurescript clojure/clojurescript: Clojure to JS compiler

Numbers

    ClojureScript currently only supports integer and floating point literals that map to JavaScript primitives
        Ratio, BigDecimal, and BigInteger literals are currently not supported
        Equality on numbers works like JavaScript, not Clojure: (= 0.0 0) => true

Kotlin JavaScript Interop | Kotlin Blog

Nim Nim Backend Integration

Features or modules that the JavaScript platform does not support are not available. This includes:

    manual memory management (alloc, etc.)
    casting and other unsafe operations (cast operator, zeroMem, etc.)
    file management
    most modules of the Standard library
    proper 64 bit integer arithmetic
    unsigned integer arithmetic

Dart


 

 

Jun 22, 2016 10:07

Error control flow in javascript promise chains (bluebird)

Posted by admin |

You can catch an error, but what does that mean for the control flow?

Consider this test script:

const P = require('bluebird')
function bad(){
return sdfffsf // this will throw an error
}
P.resolve(8).then(x=>x).then(bad).catch(e=>console.log('We got an error' + e)).then(x=>console.log('We got here' + x))

That script will print "We got here". The chain was not terminated early due to the error, because we put an error handler in between the function that threw the error and the function that printed to the console.

However, this will not print "We got here" because the error handler is after the print statement.

const P = require('bluebird')
function bad(){
return sdfffsf
}
P.resolve(8).then(x=>x).then(bad).then(x=>console.log('We got here' + x)).catch(e=>console.log('We got an error' + e))

 

So in a nutshell, .catch allows you to skip from the point of error and resume execution in the pipeline at an arbitrary point down the line. Remember to rethrow the error unless you want the rest of the pipeline after the catch handler to get executed.

Jun 18, 2016 01:00

Making find ignore directories or other stuff with -prune

Posted by admin |

(Warning: correct syntax with faulty explanations follow)

This was a real head scratcher for me. There is a -prune flag you can add to the find command on e.g. the Linux command line. It prunes stuff. So my first thought was that it takes an argument after itself for what needs to be pruned. It does not.

Instead it takes arguments before itself and uses them for what to prune out of the find results. But wait, it gets weirder: -prune returns true, which means that the stuff in front of -prune will still be there. What you need is to put an -o flag after prune. Now what is that? The total amount of documentation in the find man page about -o on my Ubuntu 16.04 is this:

       The POSIX standard specifies parentheses `(', `)', negation `!' and the `and' and `or' operators ( -a, -o).

So -o is the or operator. And -prune returns true. I don't know what programming languages you are used to, but in the ones I am used to, if the left hand side returns true with the or operator, the right hand side is not evaluated at all. If you want the right hand side to be evaluated too, you would stick an and operator in between.

So anyway, here is the way to do it

find [stuff you do not want to find] -prune -o [stuff you want to find] -print

You also need the -print flag at the end, because reasons. I guess the implicit -print you usually get in find, gets lost somewhere. Without an explicit -print, it prints. Everything.

Incidentally, if you change the -o to an -a, nothing gets printed.

Actually I think I just got it, one should think like this:

find [path] - "I'm gonna find anythyng in my path. Anything"

[stuff you do not want to find] - find all this stuff, yeah  this is what matched

-prune - "Return true! Because reasons"

-o - Ignore that shit, just terminate it, let's instead talk about this:

[stuff you want to find] - The stuff I really want. It magically got here because -prune did not return true for it. Or whatever.

-print - Hi, I'm print. I crowd out implicit prints, maybe. And I bind tight to the right hand side, so never heard of the left hand stuff.

So the or operator gets false for the files and dirs not matched by -prune, so it tries the right hand side. But wait, if this is the way it works, maybe -prune is kind of redundant. Yup, on my machine these give the same results back:

$ find -path "*/node_modules/*" -prune -o -name "*.js" -print
$ find -path "*/node_modules/*" -o -name "*.js" -print

Go figure. Maybe they are not always equivalent.
 

 

Jun 16, 2016 11:05

New features of Javascript/ECMAScript I am starting to use

Posted by admin |

Well, they may not in all cases be new to the world but here goes:

 

for ... of

Coming from python this is a no-brainer. Proper iteration over an array without getting properties

Object.keys() - JavaScript | MDN

Again, coming from python it is nice to go through the keys of an object (dictionary-style)

Arrow functions

Saves on keystrokes, and makes code more concise

Templates

It took a while to get used to the grave accents, but the fact that you can have multi line strings and have placeholders make this one interesting. Again, similar to python.

Maps

And instead of relying on Object.keys(), why not use a proper map/dictionary?

And here are things I will start to use I think:

Learning ES6: Enhanced object literals | Ben Ilegbod

From that page:

function getCar(make, model, value) {
	return {
		// with property value shorthand
		// syntax, you can omit the property
		// value if key matches variable
		// name
		make,  // same as make: make
		model, // same as model: model
		value, // same as value: value

		// computed values now work with
		// object literals
		['make' + make]: true,

		// Method definition shorthand syntax
		// omits `function` keyword & colon
		depreciate() {
			this.value -= 2500;
		}
	};
}

Ok, it turned out I needed all of those object literal improvements today, so it is now in usage by me. I needed an update to run on the nedb datbase and set a property which name is not known until runtime, so the weird [] construct was used (is Javascript turning into Perl? Using all letters?).  Before that I solved that conundrum by constructing JSON with string concatenation and then parse the result which was awkward. The shorthand for key-values worked fine in module.exports, and shorter formats of functions worked fine too.

Things I am not sure how I would benefit from using in my current style:

Symbol - JavaScript | MDN - Invisible properties, kind of.

Typed Arrays in ECMAScript 6 - Good if you work with binary data, e.g. interfacing with libraries in other languages.

Weak Maps - A way to associate data to objects which data go away (gets garbage collected) with the object.

Things I may stay away from:

Does HTML comment <!-- act as a single-line comment in JavaScript, and why? - Stack Overflow

Actually this is not new, more of a placeholder in ECMAScript documenting current browser behaviour.

Things that disappeared

Array comprehensions - were introduced and then removed(!)

 

 

Jun 11, 2016 12:50

javascript-object-templates: Pre-define what goes into a JSON-like object

Posted by admin |

You can pre-define what goes into a JSON-like object with this:

javascript-object-templates

Jun 05, 2016 10:28

tryThisforAWhile: Try something for a while in a javascript promise chain

Posted by admin |

Uses the promise-retry library. The idea is to have a function that retries something a couple of times, and checks if it succeeds. Failure is defined as the function you're trying is either throwing an exception, which is already handled by promise-retry, or, which is the new thing, failure can also be returning a value that a test function deems false. tryThisforAWhile takes the same parameters as promise-retry, with the addition of a "test" property in the config object, that references the test function. Changes to the code are likely. For example the test functions may in the future return true or false instead of throwing. And the test function should probably be curried so that it can be configured with testing criteria in the pipeline.

Example usage (warning, this is alpha code):

const _ = require('lodash')

const P = require('bluebird')

const repeat = require('promise-retry')

P.resolve('foo')
.then(tryThisforAWhile({retries:3, test:neverAcceptFn}, unreliableNetworkCall))
.then(continueWithSomethingElse)

function acceptFn(item) {
    console.log('Accept function triggered')
    return item
}
function neverAcceptFn(item) {
    console.log('Never accept function triggered')
    // Throw some kind of Error. This is a custom one.
    throw new utils.ApplicationError('Validation error', "I will reject anything")
}

function tryThisforAWhile(config, fn) {
    // accepts a config object according to the specifications of
    // https://www.npmjs.com/package/promise-retry
    // with the addition of a test property that should be assigned
    // a test function which should throw an exception if the test fails,
    // otherwise return the item

    return _.curry(_tryThisforAWhile)(config, fn)

    function _tryThisforAWhile(config, fn, item) {
        return repeat(config, function(retry, number) {
            return fn(item).then(config.test).catch(retry)
        })
    }
}
Jun 03, 2016 10:20

Understanding Alan Kay's concepts

Posted by admin |

...would probably be very enlightening. I think some time I will go through this post: Ask HN: Relationship between OO and functional programming? | Hacker News

 

And see if I can make heads or tails of the concepts.

 My guess some of this reasoning underlies current systems such as clojure and datomic. Some bullet points of quotes from the text:

  •  "world-line" ideas
  • Gelernter's Linda "coordination language" as an approach to do loose coupling via description matching in a general publish and describe manner
  • McCarthy's Temporal Logic: "Real Functions in Time"
  • But John [McCarthy] fixed it by adding an extra parameter to all "facts" that represented the "time frame" when a fact was true. This created a simple temporal logic, with a visualization of "collections of facts" as stacked "layers" of world-lines.
  • Christopher Strachey -- a great fan of Lisp and McCarthy -- who realized that many kinds of programming could be unified and also be made safer by always using "old" values (from the previous frame) to make new values, which are installed in a the new frame.
  • the programming language Lucid, by Ashcroft and Wadge, which extended many of Strachey's ideas ...
  • In this model -- again partly from McCarthy, Strachey, Simula, etc., -- "time doesn't exist between stable states": the "clock" only advances when each new state is completed. The CPU itself doesn't act as a clock as far as programs are concerned.
  • This gives rise to a very simple way to do deterministic relationships that has an intrinsic and clean model of time.
  • For a variety of reasons -- none of them very good -- this way of being safe lost out in the 60s in favor of allowing race conditions in imperative programming and then trying to protect against them using terrible semaphores, etc which can lead to lock ups.
  •  This got deeper if one was aware of how Lisp 1.5 had been implemented with the possibility of late bound parameter evaluation -- FEXPRs rather than EXPRs -- the unevaluated expressions could be passed as parameters and evaled later. This allowed the ungainly "special forms" (like the conditional) to be dispensed with, they could be written as a kind of vanilla lazy function.
  • By using the temporal modeling mentioned above, one could loosen the "gears" of "eval-apply" and get functional relationships between temporal layers via safe messaging.
     
Jun 03, 2016 09:40

Javascript destructuring for named parameters

Posted by admin |

Here is one way, adapted from 11. Parameter handling :

function selectEntries({ start, end, step }) {
    console.log(end)
}

can be called like this:

selectEntries({end:7})
>> 7

In node 5.7.0 use the flag:

--harmony_destructuring
May 28, 2016 02:12

"node.js equivalent of python's if __name__ == '__main__' "

Posted by admin |

node.js equivalent of python's if __name__ == '__main__' - Stack Overflow

 

if (!module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else
}

 

May 25, 2016 03:15

RPC built into child_process.fork in Node.js for remote calling objects

Posted by admin |

This module, called "remote.js" can be required into a module (let's call it "child_module") and then if  child_module has been forked from Node.js, the mother process can send commands to any object in child_module, that has been exposed by module.exports.

Here is some example code in child_module, where we want to be able to execute "foo.bar(params)" remotely from the mother process:

const remote = require('./remote')
remote.install(module)

const foo = require('foo') // some module
foo.bar(params) // some function call, just an example

module.exports = {foo: foo} // make sure it is visible for remote

 

Here is the code for remote.js that child_module requires:

// This module allows the calling module's exported objects'
// functions/methods to be called over RPC, from the module that forked it
// useful for testing
module.exports = {
    install: install
}

const P = require('bluebird')

function install(callingModule) {
    process.on('message', function(payload) {
            var result = callingModule.exports[payload.objectName][payload.functionName](payload.parameters)
            if (payload.isFunctionCall) { // return stuff if true, otherwise not
                P.resolve(result).done(  // TODO use standard promise
                    function(res) {
                        process.send({
                            itemName: payload.objectName,
                            functionName: payload.functionName,
                            result: res
                        })
                    }) // end done
            } // endif
        } // end process.on function
    ) // end process.on
}

It works with promises by wrapping teh return value of the function call in one (which will do nothing if it is already a promise) and the resolve it.

Calling a function from the mother module would be something like this:

var childp = child_process.fork(`${__dirname}/child_module.js`
childp.send({
            objectName: 'foo',
            functionName: 'bar',
            parameters: params,
            isFunctionCall: true
        })

And to catch a return value something like this:

childp.on('message', function(payload){
 console.log("Payload from client is: " + payload)

}
May 18, 2016 03:30
Ads