diff options
author | Urban Müller | 2017-06-06 15:21:48 +0200 |
---|---|---|
committer | Urban Müller | 2017-06-06 15:21:48 +0200 |
commit | 7ef973af86c070965a4d7c1caf3b13844c4c741b (patch) | |
tree | b8ce39c6924ec2b895a639a3a0972b4a4da4726a | |
parent | 9e266afd380229e578c1b4dc2e32b5506dd99e57 (diff) | |
download | itools-7ef973af86c070965a4d7c1caf3b13844c4c741b.tar.gz itools-7ef973af86c070965a4d7c1caf3b13844c4c741b.tar.bz2 itools-7ef973af86c070965a4d7c1caf3b13844c4c741b.zip |
add filter(), cut(), askey()
-rw-r--r-- | it_pipe.class | 48 | ||||
-rwxr-xr-x | tests/it_pipe.t | 2 |
2 files changed, 42 insertions, 8 deletions
diff --git a/it_pipe.class b/it_pipe.class index 281ee5f..5ab7e8a 100644 --- a/it_pipe.class +++ b/it_pipe.class @@ -85,6 +85,16 @@ function map($expr) } /** + * Apply an expression to every line + */ +function filter($expr) +{ + $this->lines = it::filter($expr, $this->lines); + + return $this; +} + +/** * Convert pipe from utf8 to iso-latin */ function latin() @@ -101,17 +111,14 @@ function utf8() } /** - * Return contents of pipe as key->val pair (key must be tab separated) + * Select cols from tab-separated cols in each line and tab-joins them again. Key order relevant. */ -function keyval() +function cut($picks) { - foreach ($this->lines as $line) - { - list($key, $val) = explode("\t", $line, 2); - $result[$key] = $val; - } + foreach ($this->lines as $idx => $line) + $this->lines[$idx] = join("\t", it::filter_keys(explode("\t", $line), $picks, ['reorder' => true])); - return (array)$result; + return $this; } /** @@ -128,6 +135,31 @@ function swap() return $this; } +/** + * Return contents of pipe as key->val pair (key must be tab separated). + */ +function keyval() +{ + foreach ($this->lines as $line) + { + list($key, $val) = explode("\t", $line, 2); + $result[$key] = $val; + } + + return (array)$result; +} + +/** + * Return contents of pipe as array keys with value true + */ +function askey() +{ + foreach ($this->lines as $line) + $result[$line] = true; + + return (array)$result; +} + function ED() { ED($this->lines); diff --git a/tests/it_pipe.t b/tests/it_pipe.t index e8fa4e8..93957b5 100755 --- a/tests/it_pipe.t +++ b/tests/it_pipe.t @@ -9,3 +9,5 @@ is(json_encode((new it_pipe(['data' => ["\t", "1\t2"]]))->csv()), '[{"fie is(json_encode((new it_pipe(['data' => ["a\tb", "1\t2"]]))->csv("c,d")), '[{"c":"1","d":"2"}]'); is(json_encode((new it_pipe(['data' => ["a\tb", "1\t2"]]))->csv(['forceschema' => "c,d"])), '[{"c":"1","d":"2"}]'); is(json_encode((new it_pipe(['data' => ["a b\tb", "1\t2"]]))->csv(['fixcolnames' => true])), '[{"a_b":"1","b":"2"}]'); + +is(json_encode((new it_pipe(['data' => "a\nb\n"]))->askey()), '{"a":true,"b":true}'); |