From 16bf66e5cf5c537441a98001eae9368d4bae7317 Mon Sep 17 00:00:00 2001 From: James Halliday Date: Thu, 8 Jul 2010 22:16:18 -0800 Subject: [PATCH] more examples --- README.markdown | 42 ++++++++++++++++++++++++++++++++++++++++-- examples/negative.js | 10 ++++++++++ package.json | 2 +- 3 files changed, 51 insertions(+), 3 deletions(-) create mode 100755 examples/negative.js diff --git a/README.markdown b/README.markdown index 1bf14c1..1fb09e8 100644 --- a/README.markdown +++ b/README.markdown @@ -5,8 +5,46 @@ Traverse and transform objects by visiting every node on a recursive walk. Examples ======== -JSON Scrubbing Example ----------------------- +These examples use node.js, but the module should work without it. + +Collect Leaf Nodes +------------------ + var sys = require('sys'); + var Traverse = require('traverse').Traverse; + + var acc = []; + Traverse({ + a : [1,2,3], + b : 4, + c : [5,6], + d : { e : [7,8], f : 9 } + }).forEach(function (x) { + if (this.isLeaf) acc.push(x); + }); + sys.puts(acc.join(' ')); + + /* Output: + 1 2 3 4 5 6 7 8 9 + */ + +Replace Negative Numbers +------------------------ + var sys = require('sys'); + var Traverse = require('traverse').Traverse; + + var fixed = Traverse([ + 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } + ]).modify(function (x) { + if (x < 0) this.update(x + 127); + }).get() + sys.puts(sys.inspect(fixed)); + + /* Output: + [ 5, 6, 124, [ 7, 8, 125, 1 ], { f: 10, g: 114 } ] + */ + +Scrub and Collect Functions +--------------------------- Suppose you have a complex data structure that you want to send to another process with JSON over a network socket. If the data structure has references to diff --git a/examples/negative.js b/examples/negative.js new file mode 100755 index 0000000..b4a36be --- /dev/null +++ b/examples/negative.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +var sys = require('sys'); +var Traverse = require('traverse').Traverse; + +var fixed = Traverse([ + 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } +]).modify(function (x) { + if (x < 0) this.update(x + 127); +}).get() +sys.puts(sys.inspect(fixed)); diff --git a/package.json b/package.json index 89ff72a..d2727d8 100644 --- a/package.json +++ b/package.json @@ -10,5 +10,5 @@ "repository" : { "type" : "git", "url" : "http://github.com/substack/js-traverse.git" - }, + } }