1
\$\begingroup\$

I was wondering which code might be better. I'm abstracting away the rote code as follows:

type InvokerArgs = any[]
interface InvokerFunctions {
  /**
  * send message to colleague
  */
  sendMessage: (smid: number, message: string) => InvokerArgs
  notifyOnline: (smid: number, firstTime: boolean) => InvokerArgs
}

var invokerFunctions = <InvokerFunctions> [
  'sendMessage',
  'notifyOnline'
].reduce((functions, functionName) => {
  functions[functionName] = (...args) => {
    return [functionName].concat(args)
  }
  return functions
}, {})

export = invokerFunctions

/*** Example ***/
import invokers = require('invokers')
invoke(invokers.sendMessage(46257, 'Hi, partner!'))

This seems pretty nice since the core functionality is concise, simple and easy to read. The interface makes it so you can see what each function takes.

/*** Alternative implementation ***/

function baseInvokerArgs2 (args) {
  // TypeScript in VS 2013 doesn't let me create an interface for
  // `Function` with the `name` property
  return [(<string> (<any>args.callee).name)].concat(_.toArray(args))
}

/**
* send message to colleague
*/
export function sendMessage (smid: number, message: string): InvokerArgs {
  return baseInvokerArgs2(arguments)
}

export function notifyOnline (smid: number, firstTime: boolean): InvokerArgs {
  return baseInvokerArgs2(arguments)
}

/*** Example ***/
import invokers = require('invokers')
invoke(invokers.sendMessage(46257, 'Hi, partner!'))

This alternative solution seems like it's more verbose. But I don't need to repeat the function name like in the previous version. But I do need to repeat the return statement with its function call.

At this time I think I like the first solution more, but maybe just because it is more clever. But it doesn't take advantage of some of TypeScripts stronger typing by generating the functions on the fly, so if I miss copying the name over the function won't actually be there even though the interface is or vice versa.

If it was pure JavaScript with no IntelliSense I would probably just go with the first solution with comments about the parameters.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.