Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created March 6, 2015 02:21
Show Gist options
  • Save nobeans/1a7ded47d04f0c3754b2 to your computer and use it in GitHub Desktop.
Save nobeans/1a7ded47d04f0c3754b2 to your computer and use it in GitHub Desktop.
Catn with pipeline style by Groovy
def fileContents = { fileName, encoding -> new File(fileName).getText(encoding) }
def toLines = { text -> text.split(/\r?\n/).toList() }
def sizePair = { lines -> [lines.size(), lines] }
def format = { max, lines ->
def size = "$max".size() + 1
def zipped = [(1 .. max), lines].transpose()
zipped.collect { index, line -> String.format("%${size}d: %s", index, line) }
}
def toUnlines = { lines -> lines.join(System.getProperty('line.separator'))}
def catn = fileContents >> toLines >> sizePair >> format >> toUnlines >> this.&println
catn('/tmp/hello.txt', 'UTF-8')
@nobeans
Copy link
Author

nobeans commented Mar 6, 2015

クロージャの出し入れがなければクロージャコレクションとしてのPipelineクラスいらなくてシンプルですね。
元ネタはこちら: http://d.hatena.ne.jp/Kazuhira/20120422/1335092611

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment