Facebook Interview Question! Can you write your own High Order MAP Function? | Product-Based Company

แชร์
ฝัง
  • เผยแพร่เมื่อ 16 พ.ย. 2024

ความคิดเห็น • 3

  • @theindiancolumbus1
    @theindiancolumbus1 4 หลายเดือนก่อน +2

    By the way map not always return same as input type. Transform can decide output type. so type U also may required.

  • @aliasU2
    @aliasU2 9 หลายเดือนก่อน

    thanks !! clear explanation. A better solution could have been by creating an extension on Collection, so that it can be used like Swift map function

  • @iamsanketray
    @iamsanketray 3 หลายเดือนก่อน

    Sorry, but your solution is not 100% correct. The return type is wrong. If someone calls
    let arr = ["Hello", "World", "lets go"]
    print(map(arr) { $0.count })
    your solution will throw an error.
    The correct solution would be:
    func map(_ elements: [T], _ transform: (T) -> U) -> [U] {
    var results = [U]()
    for element in elements {
    results.append(transform(element))
    }
    return results
    }