Skip to content

Instantly share code, notes, and snippets.

View knowsudhanshu's full-sized avatar

Sudhanshu knowsudhanshu

  • New Delhi
View GitHub Profile
extension Sequence {
func myCompactMap<T>(_ operation: (Element) -> T?) -> [T] {
var output: [T] = []
for item in self {
if let value = operation(item) {
output.append(value)
}
}
extension Sequence {
/// Reduce: applies a given operation on elements of a given sequence and returns a single value (of same type as of the elements in given sequence) at the end
/// - Parameters:
/// - initialValue: Initial value for the operation to start
/// - operation: function that'll be applied on elements of the given sequence
/// - Returns: final value after applying operation on the elements of given sequence
func myReduce(_ initialValue: Element,
_ operation: (_ value1: Element, _ value2: Element) -> Element) -> Element {
var output: Element = initialValue
@knowsudhanshu
knowsudhanshu / myMap.swift
Last active June 19, 2021 11:25
myMap Example
extension Sequence {
func myMap<T>(_ operation: (Element) -> T) -> [T] {
var arrayAfterOperatedValues: [T] = []
for item in self {
/// Apply operation on each element (as map(_:) does)
let operatedValue = operation(item)
arrayAfterOperatedValues.append(operatedValue)
}