Giter Club home page Giter Club logo

pie's Introduction

๐Ÿ• github.com/elliotchance/pie

GoDoc Build Status

Enjoy a slice! pie is a code generator for dealing with slices that focuses on type safety, performance and immutability.

Quick Start

Install/update:

go get -u github.com/elliotchance/pie

Built-in Types

pie ships with some slice types ready to go (pun intended). These include:

These can be used without needing go generate. For example:

package main

import (
    "github.com/elliotchance/pie/pie"
    "fmt"
)

func main() {
    name := pie.Strings{"Bob", "Sally", "John", "Jane"}.
        Unselect(func (name string) {
            return strings.HasPrefix(name, "J")
        }).
        Transform(strings.ToUpper).
        Last()

    fmt.Println(name) // "SALLY"
}

Custom Types And Structs

Annotate the slice type in your source code:

type Car struct {
    Name, Color string
}

//go:generate pie Cars
type Cars []Car

Run go generate. This will create a file called cars_pie.go. You should commit this with the rest of your code. Run go generate any time you need to add more types.

Now you can use the slices:

cars := Cars{
    {"Bob", "blue"},
    {"Sally", "green"},
    {"John", "red"},
    {"Jane", "red"},
}

redCars := cars.Select(func(car Car) bool {
    return car.Color == "red"
})

// redCars = Cars{{"John", "red"}, {"Jane", "red"}}

Or, more complex operations can be chained:

cars.Unselect(func (car Car) {
        return strings.HasPrefix(car.Name, "J")
    }).
    Transform(func (car Car) Car {
        car.Name = strings.ToUpper(car.Name)
        
        return car
    }).
    Last()

// Car{"SALLY", "green"}

Limiting Functions Generated

By default all functions will be generated. This is easy to get going but creates a lot of unused code. You can limit the functions generated by chaining the function names with a dot syntax, like:

//go:generate myInts.Average.Sum myStrings.Select

This will only generate myInts.Average, myInts.Sum and myStrings.Select.

Functions

Function String Number Struct Big-O Description
All โœ“ โœ“ โœ“ n All will return true if all callbacks return true. If the list is empty then true is always returned.
Any โœ“ โœ“ โœ“ n Any will return true if any callbacks return true. If the list is empty then false is always returned.
Append โœ“ โœ“ โœ“ n A new slice with the elements appended to the end.
AreSorted โœ“ โœ“ n Check if the slice is already sorted.
AreUnique โœ“ โœ“ n Check if the slice contains only unique elements.
Average โœ“ n The average (mean) value, or a zeroed value.
Contains โœ“ โœ“ โœ“ n Check if the value exists in the slice.
Extend โœ“ โœ“ โœ“ n A new slice with the elements from each slice appended to the end.
First โœ“ โœ“ โœ“ 1 The first element, or a zeroed value.
FirstOr โœ“ โœ“ โœ“ 1 The first element, or a default value.
Join โœ“ n A string from joining each of the elements.
JSONString โœ“ โœ“ โœ“ n The JSON encoded string.
Last โœ“ โœ“ โœ“ 1 The last element, or a zeroed value.
LastOr โœ“ โœ“ โœ“ 1 The last element, or a default value.
Len โœ“ โœ“ โœ“ 1 Number of elements.
Max โœ“ โœ“ n The maximum value, or a zeroes value.
Min โœ“ โœ“ n The minimum value, or a zeroed value.
Reverse โœ“ โœ“ โœ“ n Reverse elements.
Select โœ“ โœ“ โœ“ n A new slice containing only the elements that returned true from the condition.
Sort โœ“ โœ“ nโ‹…log(n) Return a new sorted slice.
Sum โœ“ n Sum (total) of all elements.
ToStrings โœ“ โœ“ โœ“ n Transforms each element to a string.
Transform โœ“ โœ“ โœ“ n A new slice where each element has been transformed.
Unique โœ“ โœ“ nโ‹…log(n) Return a new slice with only unique elements.
Unselect โœ“ โœ“ โœ“ n A new slice containing only the elements that returned false from the condition.

FAQ

What are the requirements?

pie supports many Go versions, all the way back to Go 1.8.

What are the goals of pie?

  1. Type safety. I never want to hit runtime bugs because I could pass in the wrong type, or perform an invalid type case out the other end.

  2. Performance. The functions need to be as fast as native Go implementations otherwise there's no point in this library existing.

  3. Nil-safe. All of the functions will happily accept nil and treat them as empty slices. Apart from less possible panics, it makes it easier to chain.

  4. Immutable. Functions never modify inputs, unlike some built-ins such as sort.Strings.

How do I contribute a function?

Pull requests are always welcome.

Here is a comprehensive list of steps to follow to add a new function:

  1. Create a new file in the functions/ directory. The file should be named the same as the function. You must include documentation for your function.

  2. Update functions/main.go to register the new function by adding an entry to Functions. Make sure you choose the correct For value that is appropriate for your function.

  3. Run go generate ./... && go install && go generate ./.... The first generate is to create the pie templates, install will update your binary for the annotations and the second generate will use the newly created templates to update the generated code for the internal types. If you encounter errors with your code you can safely rerun the command above.

  4. If you chose ForAll or ForStructs, then you must add unit tests to pie/carpointers_test.go and pie/cars_test.go.

  5. If you chose ForAll, ForNumbersAndStrings or ForNumbers, then you must add unit tests to pie/float64s_test.go and pie/ints_test.go.

  6. If you chose ForAll or ForStrings, then you must add unit tests to pie/strings_test.go.

  7. Update the README to list the new functions.

Why is the emoji a slice of pizza instead of a pie?

I wanted to pick a name for the project that was short and had an associated emoji. I liked pie, but then I found out that the pie emoji is not fully supported everywhere. I didn't want to change the name of the project to cake, but pizza pie still made sense. I'm not sure if I will change it back to a pie later.

pie's People

Contributors

elliotchance avatar jhuliano avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.