Skip to content

Instantly share code, notes, and snippets.

@harryworld
Created October 1, 2014 03:15
Show Gist options
  • Save harryworld/3f268088155ba7674637 to your computer and use it in GitHub Desktop.
Save harryworld/3f268088155ba7674637 to your computer and use it in GitHub Desktop.
Arrays and Functions
  1. Define a function that takes an array with numbers and prints all the elements of the array, separated by "--"
printSpecial([12, 33, 144, 122])
# 12 -- 33 -- 144 -- 122
  1. Define a function that takes an array with numbers and returns another array where each element contains double each element in the array
doubleMyArray([10, 20, 35, 12])
# [20, 40, 70, 24]
  1. Define a function that takes an array with numbers and returns the result of multiplying each element by ten to the power of the position it's in:
superPower([1,2,3,4,5])
# 54321

# explanation: (1 x 10^0) + (2 x 10^1) + (3 x 10^2) + (4 x 10^3) + (5 x 10^4)
# explanation: (1)        + (20)       + (300)      + (4000)     + (50000)
@harryworld
Copy link
Author

#1) Define a function that takes an array with numbers and prints all the elements of the array, separated by "--"

# printSpecial([12, 33, 144, 122])
# # 12 -- 33 -- 144 -- 122

# printSpecial = (array) ->
#   array.join(" -- ")

# console.log (printSpecial([12, 33, 144, 122]) == "12 -- 33 -- 144 -- 122")

#2) Define a function that takes an array with numbers and returns another array where each element contains double each element in the array
# doubleMyArray([10, 20, 35, 12])
# # [20, 40, 70, 24]

# areArraysEqual = (a,b) ->
#   if a.length != b.length
#     return false

#   if a.length == b.length == 0
#     return true
#   else
#     if a[0] != b[0]
#       return false
#     else
#       a.shift()
#       b.shift()
#       return areArraysEqual(a,b)


# doubleMyArray = (array) ->
  # Version 1
  # newArray = []
  # for elem, index in array
  #   newArray[index] = elem * 2
  # newArray

  # Version 2
  # newArray = []
  # for elem in array
    # newArray.push(elem*2)
  # newArray

  # Version 3
  # for elem in array
  #   elem*2

# console.log areArraysEqual( doubleMyArray([10, 20, 35, 12]), [20, 40, 70, 24])

#3) Define a function that takes an array with numbers and returns the result of multiplying each element by ten to the power of the position it's in:
# superPower([1,2,3,4,5]) 
# # 54321

# # explanation: (1 x 10^0) + (2 x 10^1) + (3 x 10^2) + (4 x 10^3) + (5 x 10^4)
# # explanation: (1)        + (20)       + (300)      + (4000)     + (50000)

superPower = (array) ->
  result = 0
  for elem, index in array
    # result = result + (elem * Math.pow(10, index))
    result = result + (elem * (10 ** index))
  return result

console.log superPower([1,2,3,4,5]) == 54321
console.log superPower([8,7,3,2,1,5]) == 512378

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