charly-lang / charly

🐈 The Charly Programming Language | Written by @KCreate
https://charly-lang.github.io/charly/
MIT License
199 stars 10 forks source link

More Object & Function methods #125

Closed KCreate closed 7 years ago

KCreate commented 7 years ago

Object.swap

Object.swap temporarily replaces a property of an object with another, runs a user-defined callback and restores the original value.

const Box = {
  let a = 25
}

Object.swap(Box, "a", 30, ->(Box) {
  print(Box.a) # => 30
})

print(Box.a) # => 25

Object.assign

Object.assign copies all keys from one object to another. Remaining arguments are also copied into the target object. See MDN: Object.prototype.assign

let Box1 = {
  let name = "box1"
}

let Box2 = {
  let age = 20
}

let Box3 = Object.assign({}, Box1, Box2)

print(Box3.name) # => "box1"
print(Box3.age) # => 20

Object.copy

Object.copy creates a copy of another object. Subsequent objects are not copied.

let Box1 = {
  let name = "box"
  let age = 20
  let object = {
    let value = 2
  }
  let children = [1, 2, 3]
}

let Box2 = Object.copy(Box1)

Box1.name = "overwritten"
Box2.name # => "box"

Box1.object.value = 25
Box2.object.value # => 25

Box1.children.push(3000)
Box2.children # => [1, 2, 3, 3000]

Object.deepcopy

Object.deepcopy behaves the same as Object.copy with the only difference being that it also recursively copies subsequent objects and the childrens of arrays.

Array.deepcopy

Array.deepcopy behaves the same as Array.copy with the only difference being that it also recursively copies the children.

Function.bind

Function.bind creates a new function where the self keyword is set to the first argument. All other arguments are treated as default arguments. See MDN: Function.prototype.bind

func foo(a, b) {
  @value = a + b
}

let context = {}

const bound = foo.bind(context, 2, 2)

bound()

print(context.value) # => 4
KCreate commented 7 years ago

Closed via commits to master