Skip to content

Instantly share code, notes, and snippets.

@hagb4rd
Last active February 6, 2018 23:08
Show Gist options
  • Save hagb4rd/781a7c28cc2846c456c3 to your computer and use it in GitHub Desktop.
Save hagb4rd/781a7c28cc2846c456c3 to your computer and use it in GitHub Desktop.

###Javascript Patterns ..thx @ Sorella

####Composition

function compose() {
  var traits = [].slice.call(arguments)
  return traits.reduce(function(result, trait) {
    for (var k in trait) 
      if (k in result)  throw new Error("Duplicated property: " + k)
      else              result[k] = trait[k]
    return result
  }, {})
}

var CanBreath = {
  breath: function() {
    return "*" + this.name + " breathes*\n"
  }
}

var CanSpeak = {
  speak: function(what) {
    return '"' + what + '," says ' + this.name + "\n"
  }
}

var Alice = compose(CanBreath, CanSpeak, { name: "Alice" })
var WhiteRabbit = compose(CanBreath, CanSpeak, { name: "the White Rabbit" })
var Dinah = compose(CanBreath, { name: "Dinah" })

console.log(
  Dinah.breath(),
  WhiteRabbit.speak("Oh my fur and whiskers! I am late, I am late!"),
  Alice.speak("A rabbit with a clock! How curious!")
)

####Inheritance

var Being = {
  inherit: function(characteristics) {
    var newBeing = Object.create(this)
    for (var k in characteristics) newBeing[k] = characteristics[k]
    return newBeing
  }
}

var Animal = Being.inherit({
  breath: function() {
    return "*" + this.name + " breathes*\n"
  }
})

var Human = Animal.inherit({
  speak: function(what) {
    return '"' + what + '," says ' + this.name + "\n"
  }
})

var Anthropomorphised = Animal.inherit({
  speak: function(what) {
    return '"' + what + '," says ' + this.name + "\n"
  }
})

var Alice = Human.inherit({
  name: 'Alice'
})

var WhiteRabbit = Anthropomorphised.inherit({
  name: 'the White Rabbit'
})

var Dinah = Animal.inherit({
  name: "Dinah"
})

console.log(
  Dinah.breath(),
  WhiteRabbit.speak("Oh my fur and whiskers! I am late, I am late!"),
  Alice.speak("A rabbit with a clock! How curious!")
)

#####Contact

irc.freenode.net ##javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment