Skip to content
This repository has been archived by the owner on Mar 25, 2018. It is now read-only.

guides: options (and default) passing patterns #78

Closed
eljefedelrodeodeljefe opened this issue Feb 8, 2016 · 2 comments
Closed

guides: options (and default) passing patterns #78

eljefedelrodeodeljefe opened this issue Feb 8, 2016 · 2 comments
Labels

Comments

@eljefedelrodeodeljefe
Copy link
Contributor

A common pattern probably in any node programming style, is to pass options. Contrary to, say golang, it's rather common to pass some let options = {}. Especially on OOP js I assume this is heavily used for class instance configurations.

However, using plain js can sort of make a quick end to this approach, when used with nested objects.

Even though this might be a small guide and pattern this could lead to better style of the community if we'd advise for a solution. Object.assign(defaultObj, [...objs]) could now be nicely used for this. See examples (old and new below):

'use strict'

function oldApi (options) {
  let opts = options || {}
  opts.name = options.name || 'the default name'
  opts.test.count = options.test.count || 1
  return opts
}

let testOptions_1 = {
  name: 'better name',
  test: {
    count: 2
  }
}
console.log(oldApi(testOptions_1));

// let testOptions_fail = {
//   name: 'better name'
// }
// console.log(oldApi(testOptions_fail)); this will fail ->
// TypeError: Cannot read property 'count' of undefined

function api (options) {
  const someDefault = {
    name: 'the default name',
    test: {
      count: 1
    }
  }
  let opts = Object.assign(someDefault, options)
  return opts
}

let testOptions_2 = {
  name: 'better name',
  test: {
    count: 2
  }
}
console.log(api(testOptions_2));

// let testOptions_success = {
//   name: 'better name'
// }
// console.log(api(testOptions_success)); // this will not fail
@eljefedelrodeodeljefe
Copy link
Contributor Author

The reason, why this is also not proliferated is that it is fairly new in v8 (Chrome 45) https://bugs.chromium.org/p/v8/issues/detail?id=4007

@Trott
Copy link
Member

Trott commented Mar 13, 2018

Closing as this repository is dormant and likely to be archived soon. If this is still an issue, feel free to open it as an issue on the main node repository.

@Trott Trott closed this as completed Mar 13, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants