User Tools

Site Tools


js:coding

JavaScript : Coding

Destructuring

Imagine a function that transforms coordinates from one coordinate system to another:

function convert(x, y, fromSRS, toSRS) {}

Looks good, means trouble.

Firstly the coordinates: The orders lat/lon and lon/lat are both commonly used. Secondly the spatial reference systems: You may want default systems for both whether or not the other one is given. Enters destructuring.

function convert({x, y, fromSRS = 'EPSG:25832', toSRS = 'EPSG:4326'}) {}

Inside the function you can use x, y, fromSRS, toSRS as before. However, you call it like this:

convert({
  x: 7.1,
  y: 50.7,
  fromSRS: 'EPSG:4326',
  toSRS: 'EPSG:25832'
})

Default Objects

In order to set default attributes you may consider

const loremIpsum = { lorem: 'LOREM', ipsum: 'IPSUM'}
 
function fullLoremIpsum(loremIpsum) {
  loremIpsum.lorem = loremIpsum.lorem || 'lorem'
  loremIpsum.ipsum = loremIpsum.ipsum || 'ipsum'
  loremIpsum.dolor = loremIpsum.dolor || 'dolor'
  loremIpsum.sit = loremIpsum.sit || 'sit'
  loremIpsum.amet = loremIpsum.amet || 'amet'
  return loremIpsum
}
 
console.log(fullLoremIpsum(loremIpsum))

(like I did for a very long time). Don't. Object.assign allows for simpler and more readable code:

const loremIpsum = { lorem: 'LOREM', ipsum: 'IPSUM'}
 
function fullLoremIpsum(loremIpsum) {
  return Object.assign({
    lorem: 'lorem',
    ipsum: 'ipsum',
    dolor: 'dolor',
    sit: 'sit',
    amet: 'amet'
  }, loremIpsum)
}
 
console.log(fullLoremIpsum(loremIpsum))

Both pieces of code yield

{
  lorem: 'LOREM',
  ipsum: 'IPSUM',
  dolor: 'dolor',
  sit: 'sit',
  amet: 'amet'
}

Method chaining

Enabling method chaining is dead simple. Just make the chainable methods return this.

lass Car {
  constructor(brand, model, color, rightSidedSteering) {
    this.brand = brand
    this.model = model
    this.color = color
    this.rightSidedSteering = rightSidedSteering
  }
 
  setBrand(brand) {
    this.brand = brand
    return this
  }
 
  setModel(model) {
    this.model = model
    return this
  }
 
  setColor(color) {
    this.color = color
    return this
  }
 
  setSteeringWheelRight(rightSidedSteering) {
    this.rightSidedSteering = rightSidedSteering
    return this
  }
 
  show() {
    console.table({
      brand: this.brand,
      model: this.model,
      color: this.color,
      'steering wheel to the right': this.rightSidedSteering
    })
    return this
  }
}
 
new Car("Bentley", "Bentayga V8", 'cool slate')
  .setColor("alter ego")
  .setSteeringWheelRight(true)
  .show()

And here's the output (turned into a DokuWiki table):

(index) Values
brand 'Bentley'
model 'Bentayga V8'
color 'alter ego'
steering wheel to the right true
js/coding.txt · Last modified: 2021/07/22 01:14 by jupp