Skip to content

Instantly share code, notes, and snippets.

@AllGistsEqual
Last active February 11, 2020 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllGistsEqual/d734f935b92c79ecc6e64651e0a10b6c to your computer and use it in GitHub Desktop.
Save AllGistsEqual/d734f935b92c79ecc6e64651e0a10b6c to your computer and use it in GitHub Desktop.
// our base for making copies
const baseUnit = {
movement: 10,
hp: 100,
attributes: {
str: 12,
dex: 8,
con: 18,
},
}
console.log(baseUnit)
// => { movement: 10, hp: 100, attributes: { str: 12, dex: 8, con: 18 } }
// a simple copy with nothing new but a name
const createUnitCopy = (base, name) => ({
...base,
name,
})
const unitCopy = createUnitCopy(baseUnit, 'Hansel')
console.log(baseUnit)
// => { movement: 10, hp: 100, attributes: { str: 12, dex: 8, con: 18 } }
console.log(unitCopy)
// => { movement: 10, hp: 100, attributes: { str: 12, dex: 8, con: 18 }, name: 'Hansel' }
// a stronger version of our regular copies
const createEnhancedUnitCopy = (base, name, newstr) => {
const { attributes, ...rest } = base
attributes.str = newstr
return {
...rest,
attributes,
name,
}
}
const betterUnit = createEnhancedUnitCopy(baseUnit, 'Gretel', 23)
console.log(baseUnit)
// => { movement: 10, hp: 100, attributes: { str: 23, dex: 8, con: 18 } }
console.log(unitCopy)
// => { movement: 10, hp: 100, attributes: { str: 23, dex: 8, con: 18 }, name: 'Hansel' }
console.log(betterUnit)
// => { movement: 10, hp: 100, attributes: { str: 23, dex: 8, con: 18 }, name: 'Gretel' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment