Skip to content

Commit

Permalink
Add function to make elements in an array unique
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdifran committed Sep 4, 2023
1 parent e23c19a commit 0e57f3e
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Sources/AppFoundations/Extensions/Array/Array+Modifying.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// File.swift
//
//
// Created by Mark DiFranco on 2023-09-04.
//

import Foundation

public extension Array {

/// Returns a new array with the provided `element` inserted.
/// - parameter element: The element to insert.
/// - returns: A new array with the provided `element` inserted.
func inserting(_ element: Element) -> Self {
self + [element]
}
}
24 changes: 24 additions & 0 deletions Sources/AppFoundations/Extensions/Array/Array+Unique.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//
// Array+Unique.swift
//
//
// Created by Mark DiFranco on 2023-09-04.
//

import Foundation

public extension Array where Element: Equatable {

mutating func madeUnique() {
self = makingUnique()
}

func makingUnique() -> Self {
reduce([]) { (partialResult, element) in
if partialResult.contains(element) {
return partialResult
}
return partialResult.inserting(element)
}
}
}
51 changes: 51 additions & 0 deletions Tests/AppFoundationsTests/Extensions/Array/Array+Unique.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//
// Array+Unique.swift
//
//
// Created by Mark DiFranco on 2023-09-04.
//

import XCTest

final class Array_Unique: XCTestCase {

var sut = [String]()

func test_madeUnique_returnsUniqueElements() {
// Arrange
sut = ["One", "One", "Two", "One", "Three"]
let expectedResult = ["One", "Two", "Three"]

// Act
sut.madeUnique()

// Assert
XCTAssertEqual(sut, expectedResult)
}

func test_makingUnique_returnsUniqueElements() {
// Arrange
sut = ["One", "One", "Two", "One", "Three"]
let expectedResult = ["One", "Two", "Three"]

// Act
let result = sut.makingUnique()

// Assert
XCTAssertEqual(result, expectedResult)
}

func test_makingUnique_performance() {
// Arrange
sut = Array(repeating: "Hello World", count: 100_000)
let expectedResult = ["Hello World"]

// Act
self.measure {
let result = sut.makingUnique()

// Assert
XCTAssertEqual(result, expectedResult)
}
}
}

0 comments on commit 0e57f3e

Please sign in to comment.