A DSL for Data Manipulation

Related tags

Utility Underscore.m
Overview

Underscore.m

About Underscore.m

Underscore.m is a small utility library to facilitate working with common data structures in Objective-C.
It tries to encourage chaining by eschewing the square bracket]]]]]].
It is inspired by the awesome underscore.js.

Real world example

// First, let's compose a twitter search request
NSURL *twitterSearch = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=@SoundCloud&rpp=100"];

// ... then we fetch us some json ...
NSData *data = [NSData dataWithContentsOfURL:twitterSearch];

// ... and parse it.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions
                                                       error:NULL];

// This is where the fun starts!
NSArray *tweets = [json valueForKey:@"results"];

NSArray *processed = _array(tweets)
    // Let's make sure that we only operate on NSDictionaries, you never
    // know with these APIs ;-)
    .filter(Underscore.isDictionary)
    // Remove all tweets that are in English
    .reject(^BOOL (NSDictionary *tweet) {
        return [[tweet valueForKey:@"iso_language_code"] isEqualToString:@"en"];
    })
    // Create a simple string representation for every tweet
    .map(^NSString *(NSDictionary *tweet) {
        NSString *name = [tweet valueForKey:@"from_user_name"];
        NSString *text = [tweet valueForKey:@"text"];

        return [NSString stringWithFormat:@"%@: %@", name, text];
    })
    .unwrap;

Documentation

Documentation for Underscore.m can be found on the website.

Comments
  • Wrapped library with familiar _.function convention.

    Wrapped library with familiar _.function convention.

    Hi Robert,

    Yesterday, I went looking for an objective-C implementation of underscore and found yours! I have very impressed with the amazing property trick for implementing .functionName syntax.

    However, felt the syntax and forced chaining could a little unconventional in the sense that I believe an Underscore.js user would just want something identical as much as possible. So I wrapped your library using the _.function convention, I introduced a convention of _.functionNameC for the library user to choose Chaining, and I added _,indexOf and _.defer because I was using them in my own library.

    A few thoughts:

    1. As an optimization, I copied some common code to the _.functionName implementation. Obviously having duplicate code is not great, but I wanted to avoid unnecessary collection copying through the Wrappers. Maybe someone in the community can review this for more optimizations (maybe some implementations belong in the Wrappers and some in the _.functionName).

    2. I was originally trying to store _ in an extern rather than as a singleton, but couldn't get it to work. If you have any ideas to do that to avoid the extra [Underscore sharedInstance] calls, please do!

    3. I ended up removing some of your '- (id)init __deprecated;' for the singleton to create an instance. Hopefully that is the best approach.

    I hope you accept this pull request!

    Kevin

    opened by kmalakoff 20
  • Add support for NSString?

    Add support for NSString?

    Just thinking out loud here

    Underscore.string(@"It was the best of times, it was the worst of times")
         .downcase
         .strip(@[ @"," ]) 
         .split(@" ")
         .uniq // Array
         .join(@", ")
         .unwrap; // @"it, was, the, best, of, times, worst"
    

    Suppose there was apply for dictionaries

    Underscore.dict(data)
        .filterKeys(Underscore.isKeyPath(target))
        .defaults(kDefaultValues)
        .apply(target)
    
    question 
    opened by robb 10
  • Release preparation

    Release preparation

    I've done a bit of a tidy. Fixed a failing test and updated the pod spec. Let me know if there's anything else that needs too e done. I'd like to merge soon and then update master shortly thereafter and get cocoa pod updated.

    I also updated the pods and project settings to work with the latest Xcode.

    @robb Do you think it's worth adding Carthage support?

    enhancement 
    opened by kvnify 9
  • Add group_by method for arrays

    Add group_by method for arrays

    Say I have this array of dictionaries:

    NSArray *names = @[ @{"name" : @"john", "sex" : "male"}, @{"name" : @"alice", "sex" : "female"}, @{"name" : @"mary", "sex" : "female"}];
    

    The command names.group_by(@"sex") will return the array grouped by the sex.

    @[ @[@{"name" : @"john", "sex" : "male"}], @[@{"name" : @"alice", "sex" : "female"}, @{"name" : @"mary", "sex" : "female"}]];
    

    I think this may be possible to do right now by chaining, but would be good to have this added to the main methods in Underscore+Functional.h

    duplicate 
    opened by esusatyo 8
  • Where to import and alias?

    Where to import and alias?

    Hi Robert,

    Love the library, as I love underscore.js. Got it working with the CocoaPods installation.

    But I gotta ask, how do you install Underscore.m globally with the alias? ie. where do I put:

    #import "Underscore.h"
    #define Underscore _
    

    I tried -Prefix.pch, which worked in 0.1.0. It doesn't seem to work now. Instead, I get: Pods/Headers/Underscore.m/Underscore.h:34:3: Underscore.m requires Automatic Reference Counting to be enabled

    Thanks!

    opened by s12chung 5
  • Cocoapods ARC issue

    Cocoapods ARC issue

    You have the following code in Underscore.h:

    #if !__has_feature(objc_arc)
    # error Underscore.m requires Automatic Reference Counting to be enabled
    #endif
    

    As far as Cocoapods creates project with disabled ARC and -fobjc-arc flags for sources - project can't be builded.

    opened by rimsan 4
  • Add methods push, pop, shift, unshift to array

    Add methods push, pop, shift, unshift to array

    Hi I'm u16suzu, from CA, US.

    Thanks for good library. I'm using your library for my private project.

    BTW, I want to add these methods on my issues's title. Actually theses are Ruby's methods, not but Underscore.js.

    push: add element to tail of array pop: remove element from tail of array

    unshift: add element to head of array shift: remove element from head of array

    Thanks for read.

    opened by u16suzu 4
  • Add Sorting

    Add Sorting

    (This replaces #24 which was based against master)

    @amiel:

    I mistakenly changed the test in 864008628a620cb409a0c3220ef809d301db5eee, see the comment there.

    The intention of USAssertEqualObjects is to compare functional style methods to their equivalent chaining style. For asserting the expecting results, please use STAssertEqualObjects with an appropriate description.

    I think sortAscending should be called compare to better communicate that it will simply call compare: on the passed in objects. Since Objective-C does not have generics, there is no good way to enforce that the objects actually respond to that selector. Let's be at least clear about what's going on behind the scenes.

    Regarding sortDescending, I think a reverse helper block would prove to be more flexible. What do you think? I could also live with leaving it out entirely since you really just need to

    _.sort(array, ^(id a, id b){ [b compare:a]; }); // Return type inference FTW! 
    
    opened by robb 4
  • Add of support for 'unique' method on array wrapper

    Add of support for 'unique' method on array wrapper

    Hi,

    I added some support for 'unique' method on array wrapper.

    Here is a sample:

            NSURL *fbReposUrl = [NSURL URLWithString:@"https://api.github.com/orgs/facebook/repos"];
            NSData *data = [NSData dataWithContentsOfURL:fbReposUrl];
            NSArray *repos = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:NULL];
    
            NSArray *languages = _array(repos).pluck(@"language").reject([Underscore isNull]).unique.unwrap;
    
            NSLog(@"Unique languages used by FaceBook: %@", languages);
    
    opened by akinsella 4
  • Why wrappers are required?

    Why wrappers are required?

    Any reason to prefer wrapper over Category? Using category, we can achieve:

    @[a, b, c].map(^(NSString *string) {
        return string.capitalizedString;
    })
    

    without any wrapping, right?

    opened by yuanmai 3
  • Add `uniq`

    Add `uniq`

    AS suggested by @yn in #10

    NSArray *array = @[ @1, @2, @3, @2, @4, @1 ];
    
    NSArray *uniques = _.uniq(array); // @[ 1, @2, @3, @4 ]
    

    ~~Should probably wait until the feature/functional-style branch went into development…~~

    enhancement 
    opened by robb 3
  • Added method to ZIP multiple arrays

    Added method to ZIP multiple arrays

    Added method to zip elements passing an array of arrays that returns another array of arrays zipped. This method only works if all the sub-arrays have the same length (should i add some checks here?)

    this:

    @[@[@1, @2, @3], @[@4, @5, @6], @[@7, @8, @9]]
    

    transforms into this:

    @[@[@1, @4, @7], @[@2, @5, @9], @[@3, @6, @9]]
    

    :warning: all the arrays should have the same lenght

    I would like to add specs, but can't make the tests run. Always getting this error after pod install:

    ld: library not found for -lPods-UnderscoreTests-Expecta
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    
    enhancement 
    opened by isaacroldan 2
  • Add functions from underscore-contrib?

    Add functions from underscore-contrib?

    There are some very useful functions in underscore-contrib that are missing from underscore.js: http://documentcloud.github.io/underscore-contrib/

    My plan is to fork Underscore.m and add these methods as I need them, but I wanted to check that you are open to adding functions like these first. Thanks!

    opened by ninjudd 4
Owner
Robb Böhnke
It's dangerous to go alone,​ take this: 🖤
Robb Böhnke
Display LaTeX using SwiftUI & LaTeX DSL

Swift LaTeX Display LaTeX using MathJax. The package also provides a custom LaTeX DSL, which enables you write LaTeX the way you write SwiftUI Views.

Vaida 2 Oct 28, 2022
RandomKit is a Swift framework that makes random data generation simple and easy.

RandomKit is a Swift framework that makes random data generation simple and easy. Build Status Installation Compatibility Swift Package Manager CocoaP

Nikolai Vazquez 1.5k Dec 29, 2022
A tiny generator of random data for swift

SwiftRandom SwiftRandom is a tiny help suite for generating random data such as Random human stuff like: names, gender, titles, tags, conversations Ra

Kan Yilmaz 559 Dec 29, 2022
Functional data types and functions for any project

Swiftx Swiftx is a Swift library containing functional abstractions and extensions to the Swift Standard Library. Swiftx is a smaller and simpler way

TypeLift 219 Aug 30, 2022
A simple Pokedex app written in Swift that implements the PokeAPI, using Combine and data driven UI.

SwiftPokedex SwiftPokedex is a simple Pokedex app written by Viktor Gidlöf in Swift that implements the PokeAPI. For full documentation and implementa

Viktor G 26 Dec 14, 2022
Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data.

Pigeon ?? Introduction Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data. It is heavily inspired by React Qu

Fernando Martín Ortiz 369 Dec 30, 2022
Passing data from a couple of screen into a Model

Passing-Data Passing data from a couple of screen into a Model Introduction Hi, this video is just a representation project from this Video by Essenti

null 0 Oct 12, 2021
Measure the power output from a car or any moving vehicle from GPS data and weight

GPSDyno Measure the power output from a car or any moving vehicle from weight and GPS data of your iOS device. This is just a example project and shou

Marcelo Ferreira Barreto 0 Jan 7, 2022
Easier sharing of structured data between iOS applications and share extensions

XExtensionItem XExtensionItem is a tiny library allowing for easier sharing of structured data between iOS applications and share extensions. It is ta

Tumblr 86 Nov 23, 2022
Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings)

Swift .csv parser Taking a string containing a csv file and split it into records (aka lines) containing fields of data (aka Array of SubStrings). Par

Matthias 0 Dec 29, 2021
Framework for easily parsing your JSON data directly to Swift object.

Server sends the all JSON data in black and white format i.e. its all strings & we make hard efforts to typecast them into their respective datatypes

Mukesh 11 Oct 17, 2022
A visual developer tool for inspecting your iOS application data structures.

Tree Dump Debugger A visual developer tool for inspecting your iOS application data structures. Features Inspect any data structure with only one line

null 8 Nov 2, 2022
swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

kelvin 4 Aug 14, 2022
Swift 3 framework for accessing data in Event Registry

Swift 3 framework for accessing data in Event Registry

Pavel Pantus 8 Nov 1, 2016
A tool to convert Apple PencilKit data to Scribble Proto3.

ScribbleConverter Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation

Paul Han 1 Aug 1, 2022
Data Mapping library for Objective C

OCMapper is a data mapping library for Objective C that converts NSDictionary to NSObject

Aryan Ghassemi 346 Dec 8, 2022
A Swift DSL that allows concise and effective concurrency manipulation

NOTE Brisk is being mothballed due to general incompatibilities with modern version of Swift. I recommend checking out ReactiveSwift, which solves man

Jason Fieldman 25 May 24, 2019
NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier.

NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier. NVDate is testable and robust, we wrote intensive test to make sure everything is safe.

Noval Agung Prayogo 177 Oct 5, 2022
SwiftMoment - A time and calendar manipulation library for iOS 9+, macOS 10.11+, tvOS 9+, watchOS 2+ written in Swift 4.

SwiftMoment This framework is inspired by Moment.js. Its objectives are the following: Simplify the manipulation and readability of date and interval

Adrian Kosmaczewski 1.6k Dec 31, 2022
In our project we are interested in the manipulation of HSLA images

Projet 1 HSLA Images Réalisé par : Adil Erraad,Said El Ouardi Link to another page. HSLA Images Introduction Dans le cadre de notre projet nous nous s

null 0 Nov 7, 2021