├── .eslintrc ├── .gitignore ├── .npmignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── karma.conf.js ├── package.json ├── src ├── bm │ ├── post.txt │ └── pre.txt └── waldo.js ├── test └── finder_spec.js └── webpack.config.js /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es6": true, 5 | "mocha": true, 6 | "node": true 7 | }, 8 | "ecmaFeatures": { 9 | modules: true 10 | }, 11 | "globals": { 12 | "assert": true, 13 | "expect": true, 14 | "spyOn": true 15 | }, 16 | "rules": { 17 | "block-scoped-var": 0, 18 | "brace-style": [2, "1tbs", { "allowSingleLine": true }], 19 | "camelcase": 0, 20 | "comma-dangle": [2, "never"], 21 | "comma-spacing": [2, { "before": false, "after": true }], 22 | "comma-style": [2, "last"], 23 | "complexity": 0, 24 | "consistent-return": 0, 25 | "consistent-this": 0, 26 | "curly": [0, "multi-line"], 27 | "default-case": 0, 28 | "dot-notation": 0, 29 | "eol-last": 2, 30 | "eqeqeq": 0, 31 | "func-names": 0, 32 | "func-style": [0, "declaration"], 33 | "generator-star-spacing": [2, "after"], 34 | "guard-for-in": 0, 35 | "handle-callback-err": [2, "^(err|error|anySpecificError)$" ], 36 | "indent": [2, 2], 37 | "key-spacing": [2, { "beforeColon": false, "afterColon": true }], 38 | "max-depth": 0, 39 | // 'max-len' deviates from 'standard' 40 | "max-len": [2, 100, 4], 41 | "max-nested-callbacks": 0, 42 | "max-params": 0, 43 | "max-statements": 0, 44 | "new-cap": [2, { "newIsCap": true, "capIsNew": false }], 45 | "new-parens": 2, 46 | "no-alert": 0, 47 | "no-array-constructor": 2, 48 | "no-bitwise": 0, 49 | "no-caller": 2, 50 | "no-catch-shadow": 0, 51 | "no-cond-assign": 2, 52 | "no-console": 0, 53 | "no-constant-condition": 0, 54 | "no-control-regex": 2, 55 | "no-debugger": 2, 56 | "no-delete-var": 2, 57 | "no-div-regex": 0, 58 | "no-dupe-args": 2, 59 | "no-dupe-keys": 2, 60 | "no-duplicate-case": 2, 61 | "no-else-return": 0, 62 | "no-empty": 0, 63 | "no-empty-class": 2, 64 | "no-empty-label": 2, 65 | "no-eq-null": 0, 66 | "no-ex-assign": 2, 67 | "no-extend-native": 2, 68 | "no-extra-bind": 2, 69 | "no-extra-boolean-cast": 2, 70 | "no-extra-parens": 0, 71 | "no-extra-semi": 0, 72 | "no-extra-strict": 0, 73 | "no-fallthrough": 2, 74 | "no-floating-decimal": 2, 75 | "no-func-assign": 2, 76 | "no-implied-eval": 0, 77 | "no-inline-comments": 0, 78 | "no-inner-declarations": [2, "functions"], 79 | "no-invalid-regexp": 2, 80 | "no-irregular-whitespace": 2, 81 | "no-iterator": 2, 82 | "no-label-var": 2, 83 | "no-labels": 2, 84 | "no-lone-blocks": 0, 85 | "no-lonely-if": 0, 86 | "no-loop-func": 0, 87 | "no-mixed-requires": [0, false], 88 | "no-mixed-spaces-and-tabs": [2, false], 89 | "no-multi-spaces": 2, 90 | "no-multi-str": 2, 91 | "no-multiple-empty-lines": [2, { "max": 1 }], 92 | "no-native-reassign": 2, 93 | "no-negated-in-lhs": 2, 94 | "no-nested-ternary": 0, 95 | "no-new": 0, 96 | "no-new-func": 0, 97 | "no-new-object": 0, 98 | "no-new-require": 2, 99 | "no-new-wrappers": 2, 100 | "no-obj-calls": 2, 101 | "no-octal": 2, 102 | "no-octal-escape": 2, 103 | "no-path-concat": 0, 104 | "no-plusplus": 0, 105 | "no-process-env": 0, 106 | "no-process-exit": 0, 107 | "no-proto": 0, 108 | "no-redeclare": 2, 109 | "no-regex-spaces": 2, 110 | "no-reserved-keys": 0, 111 | "no-restricted-modules": 0, 112 | "no-return-assign": 2, 113 | "no-script-url": 2, 114 | "no-self-compare": 2, 115 | "no-sequences": 0, 116 | "no-shadow": 0, 117 | "no-shadow-restricted-names": 2, 118 | "no-spaced-func": 2, 119 | "no-sparse-arrays": 2, 120 | "no-sync": 0, 121 | "no-ternary": 0, 122 | "no-throw-literal": 2, 123 | "no-trailing-spaces": 2, 124 | "no-undef": 2, 125 | "no-undef-init": 2, 126 | "no-undefined": 0, 127 | "no-underscore-dangle": 0, 128 | "no-unreachable": 2, 129 | "no-unused-expressions": 0, 130 | "no-unused-vars": [2, { "vars": "all", "args": "none" }], 131 | "no-use-before-define": 0, 132 | "no-var": 0, 133 | "no-void": 0, 134 | "no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }], 135 | "no-with": 0, 136 | "no-wrap-func": 2, 137 | "one-var": 0, 138 | "operator-assignment": [0, "always"], 139 | "padded-blocks": [2, "never"], 140 | "quote-props": 0, 141 | "quotes": [2, "single", "avoid-escape"], 142 | "radix": 2, 143 | "semi": 0, 144 | "semi-spacing": 0, 145 | "sort-vars": 0, 146 | "space-after-keywords": [2, "always"], 147 | "space-before-blocks": [2, "always"], 148 | // 'space-before-function-parentheses' deviates from 'standard' 149 | "space-before-function-parentheses": [2, {"anonymous": "always", "named": "never"}], 150 | "space-in-brackets": 0, 151 | "space-in-parens": [2, "never"], 152 | "space-infix-ops": 2, 153 | "space-return-throw-case": 2, 154 | "space-unary-ops": [2, { "words": true, "nonwords": false }], 155 | "spaced-line-comment": [2, "always"], 156 | "strict": 0, 157 | "use-isnan": 2, 158 | "valid-jsdoc": 0, 159 | "valid-typeof": 2, 160 | "vars-on-top": 0, 161 | // 'wrap-iife' deviates from 'standard' 162 | "wrap-iife": [0, "outside"], 163 | "wrap-regex": 0, 164 | "yoda": [0, "never"] 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.tgz 3 | lib/ 4 | node_modules -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | test/ 3 | karma.conf.js 4 | .travis.yml 5 | CONTRIBUTING.md 6 | .eslintrc 7 | LICENSE 8 | Makefile 9 | webpack.config.js -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.10" 4 | before_script: 5 | - "npm install" 6 | - "export DISPLAY=:99.0" 7 | - "sh -e /etc/init.d/xvfb start" 8 | script: "karma start --single-run" 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to waldoJS 2 | 3 | Please take a moment to review this document in order to make the contribution 4 | process easy and effective for everyone involved. 5 | 6 | Following these guidelines helps to communicate that you respect the time of 7 | the developers managing and developing this open source project. In return, 8 | they should reciprocate that respect in addressing your issue or assessing 9 | patches and features. 10 | 11 | 12 | ## Using the issue tracker 13 | 14 | The issue tracker is the preferred channel for [bug reports](#bugs), 15 | [features requests](#features) and [submitting pull 16 | requests](#pull-requests), but please respect the following restrictions: 17 | 18 | * Please **do not** use the issue tracker for personal support requests. 19 | 20 | * Please **do not** derail or troll issues. Keep the discussion on topic and 21 | respect the opinions of others. 22 | 23 | 24 | 25 | ## Bug reports 26 | 27 | A bug is a _demonstrable problem_ that is caused by the code in the repository. 28 | Good bug reports are extremely helpful - thank you! 29 | 30 | Guidelines for bug reports: 31 | 32 | 1. **Use the issue search** — check if the issue has already been 33 | reported. 34 | 35 | 2. **Check if the issue has been fixed** — try to reproduce it using the 36 | latest `master` or development branch in the repository. 37 | 38 | 3. **Isolate the problem** – create a live example of a [reduced test 39 | case](http://css-tricks.com/6263-reduced-test-cases/). 40 | 41 | A good bug report shouldn't leave others needing to chase you up for more 42 | information. Please try to be as detailed as possible in your report. What is 43 | your environment? What steps will reproduce the issue? What browser(s) and OS 44 | experience the problem? What would you expect to be the outcome? All these 45 | details will help people to fix any potential bugs. 46 | 47 | Example: 48 | 49 | > Short and descriptive example bug report title 50 | > 51 | > A summary of the issue and the browser/OS environment in which it occurs. If 52 | > suitable, include the steps required to reproduce the bug. 53 | > 54 | > 1. This is the first step 55 | > 2. This is the second step 56 | > 3. Further steps, etc. 57 | > 58 | > `` - a link to the reduced test case 59 | > 60 | > Any other information you want to share that is relevant to the issue being 61 | > reported. This might include the lines of code that you have identified as 62 | > causing the bug, and potential solutions (and your opinions on their 63 | > merits). 64 | 65 | 66 | 67 | ## Feature requests 68 | 69 | Feature requests are welcome. But take a moment to find out whether your idea 70 | fits with the scope and aims of the project. It's up to *you* to make a strong 71 | case to convince the project's developers of the merits of this feature. Please 72 | provide as much detail and context as possible. 73 | 74 | 75 | 76 | ## Pull requests 77 | 78 | Good pull requests - patches, improvements, new features - are a fantastic 79 | help. They should remain focused in scope and avoid containing unrelated 80 | commits. 81 | 82 | **Please ask first** before embarking on any significant pull request (e.g. 83 | implementing features, refactoring code, porting to a different language), 84 | otherwise you risk spending a lot of time working on something that the 85 | project's developers might not want to merge into the project. 86 | 87 | Please adhere to the coding conventions used throughout a project (indentation, 88 | accurate comments, etc.) and any other requirements (such as test coverage). 89 | 90 | Adhering to the following this process is the best way to get your work 91 | included in the project: 92 | 93 | 1. If you do not have permissions to push to the upstream remote origin, 94 | [fork](http://help.github.com/fork-a-repo/) the project, clone your fork, 95 | and configure the remotes: 96 | 97 | ```bash 98 | # Clone your fork of the repo into the current directory 99 | git clone 100 | # Navigate to the newly cloned directory 101 | cd 102 | # Assign the original repo to a remote called "upstream" 103 | git remote add upstream 104 | ``` 105 | 106 | 2. If you cloned a while ago, get the latest changes from upstream: 107 | 108 | ```bash 109 | git checkout 110 | git pull upstream 111 | ``` 112 | 113 | 3. Create a new topic branch (off the main project development branch) to 114 | contain your feature, change, or fix: 115 | 116 | ```bash 117 | git checkout -b 118 | ``` 119 | 120 | 4. Commit your changes in logical chunks. Please adhere to these [git commit 121 | message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) 122 | or your code is unlikely be merged into the main project. Use Git's 123 | [interactive rebase](https://help.github.com/articles/interactive-rebase) 124 | feature to tidy up your commits before making them public. 125 | 126 | 5. Locally merge (or rebase) the upstream development branch into your topic branch: 127 | 128 | ```bash 129 | git pull [--rebase] upstream 130 | ``` 131 | 132 | 6. Push your topic branch up to your fork: 133 | 134 | ```bash 135 | git push origin 136 | ``` 137 | 138 | 7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) 139 | with a clear title and description. 140 | 141 | **IMPORTANT**: By submitting a patch, you agree to allow the project owner to 142 | license your work under the same license as that used by the project. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Angus Croll and John-David Dalton 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BUILD_DIR := lib 2 | 3 | build: 4 | @npm run prepublish 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/angus-c/waldojs.png?branch=master)](http://travis-ci.org/angus-c/waldojs) [![npm version](http://img.shields.io/npm/v/waldojs.svg)](https://npmjs.org/package/waldojs) 2 | [![Dependency Status](https://david-dm.org/angus-c/waldojs.svg)](https://david-dm.org/angus-c/waldojs.svg) 3 | 4 | # WaldoJS 5 | 6 | I got frustrated looking for specific properties and values within JavaScript object trees — so I created a utility to do it for me. 7 | 8 | Waldo lets you search globally or within specificied objects. You can search by property name, property type or property value. You can also create your own custom search functions. Waldo can be run as an [npm module](https://github.com/angus-c/waldo/tree/output_objects#1-using-the-npm-module), or a [global file](https://github.com/angus-c/waldo/tree/output_objects#2-standalone) and there's also an autogenerated [bookmarklet](https://github.com/angus-c/waldo/tree/output_objects#3-using-the-bookmarklet-in-the-browser-console) you can use for quick checks in the console. 9 | 10 | ## Overview 11 | 12 | A waldo search returns an array of Match objects... 13 | 14 | ```js 15 | var waldo = require('waldojs'); 16 | 17 | // find react properties named 'oneOfType' 18 | var React = require('react'); 19 | var matches = waldo.byName('oneOfType', React); 20 | 21 | matches[0].path; // 'SRC.PropTypes.oneOfType' 22 | matches[0].value; // [the function] 23 | matches[0].type; // 'function' 24 | ``` 25 | 26 | Running `log` over a Match, or all matches, returns a formatted text summary. 27 | 28 | ```js 29 | // global search for objects with a value of 10 30 | waldo.byValue(10).log(); // => 31 | GLOBAL.module.exports.repl._maxListeners -> (number) 10 32 | GLOBAL.module.exports.repl.rli._maxListeners -> (number) 10 33 | GLOBAL.module.exports.repl.outputStream._maxListeners -> (number) 10 34 | GLOBAL.module.exports.repl.inputStream._maxListeners -> (number) 10 35 | ``` 36 | 37 | If you use a transpiler like babel you could interact with waldo in ES 6. (Waldo is itself written in ES 6). 38 | 39 | ```js 40 | // use a destructure assignment to find a nested pattern 41 | const obj = {a: {a: 3, b: {c: 4, a: {a: {b: 4}}}}}; 42 | const matches = find.custom( 43 | (what, obj, prop) => { 44 | let {a: {b: x}} = obj[prop]; 45 | return x === 4; 46 | }, obj); 47 | matches.log(); // 'SRC.a.b.a -> (object) {a: {b: 4}}' 48 | ``` 49 | 50 | ## Installation and Usage 51 | 52 | ### 1. Using the npm module 53 | 54 | ``` 55 | npm install waldojs 56 | ``` 57 | 58 | then 59 | 60 | ```js 61 | var waldo = require('waldojs'); // ES 5 62 | ``` 63 | 64 | or 65 | 66 | ```js 67 | import waldo from 'waldojs'; // ES 6 68 | ``` 69 | 70 | ### 2. Standalone 71 | 72 | Clone this repo and run `make` to generate the standalone bundles `waldobundle.js` and `waldobundle.min.js`. The global `waldo` object will now be available to you. 73 | 74 | ### 3. Using the Bookmarklet in the Browser Console 75 | 76 | By using the supplied bookmarklet (`lib/bookmarklet.txt` - you'll need to run `make` if it isn't there) you can type waldo commands directly in the console. When run in the console waldo auto-logs all matches. 77 | 78 | ## Output 79 | 80 | ### Match 81 | 82 | Every time waldo finds an object that matches the search criteria, a `Match` object is created. Each call to waldo returns an array of `Match` objects. 83 | 84 | A `Match` instance has the following properties 85 | 86 | * `path` the property path to reach the matching object. 87 | * `prop` the name of the matching object. 88 | * `value` the value of the matching object. 89 | * `obj` the matching object 90 | * `log` function that returns a formatted string representation of the match (the array of matches also has a `log` function that returns a formatted string of all matches). 91 | 92 | ## API 93 | 94 | Waldo accepts a variety of query methods. 95 | 96 | * `byName` search the object tree for properties with this name 97 | * `byValue` search the object tree for properties with this value 98 | * `byValueCoerced` search the object tree for properties that == this value 99 | * `byType` search the object tree for properties that are an instance of the given 100 | class/constructor. 101 | * `custom` supply a custom search function 102 | 103 | Each method accepts up to 2 arguments: 104 | 105 | * `what` (required) the property, value or type to match on 106 | * `where` (optional - default is the global object) the root of the search 107 | 108 | ### byName 109 | 110 | ```js 111 | // Find properties named 'read' anywhere 112 | var matches = waldo.byName('read'); 113 | matches.length; // 1 114 | matches[0].value; // [the function] 115 | matches[0].log(); // => 116 | 'GLOBAL.module.exports.repl.inputStream.read -> (function) [object Function]' 117 | ``` 118 | 119 | ### byValue 120 | ```js 121 | // Global search for all properties with the value 10 122 | var matches = waldo.byValue(10); 123 | matches.length // => 4; 124 | 125 | // return the results as a formatted string... 126 | // (when running globally these logs appear in the console by default) 127 | matches.log(); // => 128 | GLOBAL.module.exports.repl._maxListeners -> (number) 10 129 | GLOBAL.module.exports.repl.rli._maxListeners -> (number) 10 130 | GLOBAL.module.exports.repl.outputStream._maxListeners -> (number) 10 131 | GLOBAL.module.exports.repl.inputStream._maxListeners -> (number) 10 132 | ``` 133 | 134 | ### byValueCoerced 135 | 136 | ```js 137 | // get all falsey values globally 138 | waldo.byValueCoerced(false); // => 139 | GLOBAL.deviceIsAndroid -> (boolean) false 140 | GLOBAL.deviceIsIOS -> (boolean) false 141 | GLOBAL.defaultstatus -> (string) '' 142 | GLOBAL.GitHub.support.setImmediate -> (boolean) false 143 | GLOBAL.chrome.app.isInstalled -> (boolean) false 144 | etc.. 145 | ``` 146 | 147 | ### byType 148 | ```js 149 | var a = { 150 | aa: ['x', 'y', 'z'], 151 | bb: { 152 | bbb: [1, 2, 3], 153 | ccc: 54 154 | } 155 | }; 156 | 157 | waldo.byType(Array, a); // => 158 | SRC.aa -> (object) x,y,z 159 | SRC.bb.bbb -> (object) 1,2,3 160 | ``` 161 | 162 | ### Custom 163 | 164 | The `custom` method takes 2 arguments: 165 | * `fn` - function specifying match criteria 166 | * `where` (optional) -where to search 167 | 168 | ```js 169 | // find all true values beginning with 'c' 170 | var vegetables = { 171 | carrots: { 172 | chopped: false, 173 | cleaned: true 174 | } 175 | leaks: { 176 | chopped: true, 177 | cleaned: false 178 | } 179 | }; 180 | 181 | waldo.custom(function(what, obj, prop) { 182 | return (obj[prop] === true) && (!prop.indexOf('c')); 183 | }, vegetables); // => 184 | SRC.leaks.chopped -> (boolean) true 185 | SRC.carrots.cleaned -> (boolean) true 186 | ``` 187 | 188 | ## Circular References 189 | 190 | Waldo detects circular references and cites them: 191 | 192 | ```js 193 | var a = {x: b}; 194 | var b = {y: c}; 195 | var c = {z: a}; 196 | waldo.byName('z'); 197 | ``` 198 | 199 | will log... 200 | ``` 201 | GLOBAL.c.z -> () {z: a} 202 | ``` 203 | 204 | Thanks to [John-David Dalton](https://github.com/jdalton) for adding circular reference detection as well as providing some early refactor commits. 205 | 206 | ## Testing 207 | 208 | To test both module and the standalone bundles: 209 | ``` 210 | npm test 211 | ``` 212 | 213 | To run continuous tests in watch mode: 214 | ``` 215 | npm run testc 216 | ``` 217 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | module.exports = function (config) { 2 | config.set({ 3 | 4 | // base path, that will be used to resolve files and exclude 5 | basePath: '', 6 | 7 | // list of files / patterns to load in the browser 8 | files: [ 9 | 'lib/waldobundle.min.js', 10 | 'test/finder_spec.js' 11 | ], 12 | 13 | // list of files to exclude 14 | exclude: [ 15 | 16 | ], 17 | 18 | // test results reporter to use 19 | // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' 20 | reporters: ['dots'], 21 | 22 | // web server port 23 | port: 9876, 24 | 25 | // enable / disable colors in the output (reporters and logs) 26 | colors: true, 27 | 28 | // level of logging 29 | logLevel: config.LOG_INFO, 30 | 31 | // enable / disable watching file and executing tests whenever any file changes 32 | autoWatch: true, 33 | 34 | // Start these browsers, currently available: 35 | // - Chrome 36 | // - ChromeCanary 37 | // - Firefox 38 | // - Opera 39 | // - Safari (only Mac) 40 | // - PhantomJS 41 | // - IE (only Windows) 42 | browsers: ['Firefox'], 43 | 44 | // If browser does not capture in given timeout [ms], kill it 45 | captureTimeout: 60000, 46 | 47 | // Continuous Integration mode 48 | // if true, it capture browsers, run tests and exit 49 | singleRun: false, 50 | 51 | frameworks: ['jasmine'], 52 | 53 | preprocessors: { 54 | 'src/*.js': ['webpack', 'sourcemap'], 55 | 'test/*spec.js': ['webpack', 'sourcemap'] 56 | }, 57 | 58 | plugins: [ 59 | 'karma-chrome-launcher', 60 | 'karma-firefox-launcher', 61 | 'karma-jasmine', 62 | 'karma-sourcemap-loader', 63 | 'karma-webpack' 64 | ], 65 | 66 | webpack: { 67 | module: { 68 | loaders: [ 69 | { 70 | // es6 JavaScript 71 | test: /\.js$/, 72 | loader: 'babel-loader?cacheDirectory=true', 73 | exclude: /node_modules/ 74 | } 75 | ] 76 | }, 77 | watch: true 78 | } 79 | }); 80 | }; 81 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "waldojs", 3 | "version": "0.1.9", 4 | "description": "Find things in your JS object tree", 5 | "author": "Angus Croll", 6 | "license": "MIT", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/angus-c/waldojs.git" 10 | }, 11 | "main": "lib/waldo.js", 12 | "scripts": { 13 | "bookmarklet": "cat src/bm/pre.txt lib/waldobundle.min.js src/bm/post.txt > lib/bookmarklet.txt", 14 | "bundle": "webpack", 15 | "compile": "babel --optional runtime src --out-dir lib", 16 | "env": "env", 17 | "minify": "uglifyjs lib/waldobundle.js -o lib/waldobundle.min.js", 18 | "prepublish": "npm run compile && npm run bundle && npm run minify && npm run bookmarklet", 19 | "test": "npm run prepublish && karma start --single-run", 20 | "testc": "npm run prepublish && karma start --auto-watch" 21 | }, 22 | "keywords": [ 23 | "javascript", 24 | "find", 25 | "match", 26 | "node", 27 | "properties", 28 | "search" 29 | ], 30 | "devDependencies": { 31 | "babel": "^5.8.29", 32 | "babel-core": "^5.8.29", 33 | "babel-loader": "^5.3.2", 34 | "eslint": "^1.7.3", 35 | "jasmine-core": "^2.3.4", 36 | "karma": "^0.13.14", 37 | "karma-chrome-launcher": "^0.2.1", 38 | "karma-firefox-launcher": "^0.1.6", 39 | "karma-jasmine": "^0.3.6", 40 | "karma-sourcemap-loader": "^0.3.6", 41 | "karma-webpack": "^1.7.0", 42 | "uglify-js": "^2.5.0" 43 | }, 44 | "dependencies": { 45 | "babel-runtime": "^5.5.8", 46 | "just-compare": "^1.1.19" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/bm/post.txt: -------------------------------------------------------------------------------- 1 | })(); -------------------------------------------------------------------------------- /src/bm/pre.txt: -------------------------------------------------------------------------------- 1 | javascript: (function(){ -------------------------------------------------------------------------------- /src/waldo.js: -------------------------------------------------------------------------------- 1 | import compare from 'just-compare'; 2 | 3 | const GLOBAL = (typeof window == 'object') ? window : global; 4 | 5 | const find = { 6 | byName(what, where) { 7 | return this.searchMaybe('propName', 'string', what, where); 8 | }, 9 | byType(what, where) { 10 | return this.searchMaybe('type', 'function', what, where); 11 | }, 12 | byValue(what, where) { 13 | return this.searchMaybe('value', null, what, where); 14 | }, 15 | byValueCoerced(what, where) { 16 | return this.searchMaybe('valueCoerced', null, what, where); 17 | }, 18 | custom(fn, where) { 19 | return this.searchMaybe(fn, null, null, where); 20 | }, 21 | searchMaybe(util, expected, what, where) { 22 | // integrity check arguments 23 | if (expected && typeof what != expected) { 24 | throw new Error(`${what} must be ${expected}`); 25 | } 26 | // only console.log if we are the global function 27 | if (this === GLOBAL.waldo) { 28 | GLOBAL.DEBUG = true; 29 | } 30 | return search(util, what, where); 31 | } 32 | } 33 | 34 | function search(util, what, where = GLOBAL) { 35 | util = searchBy[util] || util; 36 | 37 | let data; 38 | let alreadySeen; 39 | 40 | const path = (where == GLOBAL) ? 'GLOBAL' : 'SRC'; 41 | let queue = [{ where, path }]; 42 | let seen = []; 43 | 44 | let matches = []; 45 | matches.log = function () { 46 | this.forEach(m => m.log()); 47 | }; 48 | 49 | // a non-recursive solution to avoid call stack limits 50 | // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 51 | while ((data = queue.pop())) { 52 | let {where, path} = data; 53 | 54 | for (const prop in where) { 55 | // IE may throw errors when accessing/coercing some properties 56 | try { 57 | if (where.hasOwnProperty(prop)) { 58 | // inspect objects 59 | if ([where[prop]] == '[object Object]') { 60 | // check if already searched (prevents circular references) 61 | for ( 62 | var i = -1; 63 | seen[++i] && !(alreadySeen = compare(seen[i].where, where[prop]) && seen[i]); 64 | ); 65 | // add to stack 66 | if (!alreadySeen) { 67 | data = { where: where[prop], path: `${path}.${prop}`}; 68 | queue.push(data); 69 | seen.push(data); 70 | } 71 | } 72 | // if match detected, push it. 73 | if (util(what, where, prop)) { 74 | const type = alreadySeen ? `<${alreadySeen.path}>` : typeof where[prop]; 75 | const match = new Match( 76 | {path: `${path}.${prop}`, obj: where, prop, type}); 77 | matches.push(match); 78 | GLOBAL.DEBUG && match.log(); 79 | } 80 | } 81 | } catch(e) {} 82 | } 83 | } 84 | 85 | return matches; 86 | } 87 | 88 | const searchBy = { 89 | propName(what, where, prop) { 90 | return what == prop; 91 | }, 92 | type(what, where, prop) { 93 | return where[prop] instanceof what; 94 | }, 95 | value(what, where, prop) { 96 | return where[prop] === what; 97 | }, 98 | valueCoerced(what, where, prop) { 99 | return where[prop] == what; 100 | } 101 | }; 102 | 103 | class Match { 104 | constructor(props) { 105 | Object.assign(this, props); 106 | this.value = this.obj[this.prop]; 107 | } 108 | 109 | toString() { 110 | let {path, type} = this; 111 | return `${path} -> (${type}) ${this.logValue()}`; 112 | } 113 | 114 | logValue() { 115 | const val = this.value; 116 | // if value is an object then just toString it 117 | const isPrimitive = x => Object(x) !== x; 118 | return isPrimitive(val) || Array.isArray(val) ? 119 | val : 120 | {}.toString.call(val); 121 | } 122 | 123 | log() { 124 | console.log(this.toString()); 125 | } 126 | } 127 | 128 | // for console running 129 | GLOBAL.waldo = Object.assign({}, find, {debug: true}); 130 | 131 | export default find; 132 | -------------------------------------------------------------------------------- /test/finder_spec.js: -------------------------------------------------------------------------------- 1 | import waldo from '../lib/waldo'; 2 | 3 | const GLOBAL = (typeof window == 'object') ? window : global; 4 | 5 | GLOBAL.testObj = { 6 | obj: {d: 4}, 7 | arr1: [1, 2, 3, 4, 5], 8 | arr2: ['a', 'b', 'c'], 9 | fn: function () {}, 10 | num: 1 11 | } 12 | GLOBAL.testObj.circ = {a: 3, b: GLOBAL.testObj.obj}; 13 | 14 | let logSpy, matches; 15 | 16 | function testMatches(matches, expectedMatches) { 17 | expect(matches.length).toEqual(expectedMatches.length); 18 | expectedMatches.forEach((match, i) => { 19 | expect(matches[i].toString()).toEqual(match); 20 | }); 21 | if (GLOBAL.DEBUG) { 22 | if (expectedMatches.length) { 23 | expect(console.log).toHaveBeenCalledWith( 24 | expectedMatches[expectedMatches.length - 1]); 25 | } else { 26 | expect(console.log).not.toHaveBeenCalled(); 27 | } 28 | } 29 | } 30 | 31 | [waldo, GLOBAL.waldo].forEach(find => { 32 | describe('waldo', () => { 33 | beforeEach(() => { 34 | GLOBAL.DEBUG = null; 35 | logSpy = spyOn(console, 'log').and.callThrough(); 36 | }); 37 | 38 | describe('debug mode', () => { 39 | it('is only engaged in global version', () => { 40 | find.byName('test'); 41 | if (find === GLOBAL.waldo) { 42 | expect(GLOBAL.DEBUG).toEqual(true); 43 | } else { 44 | expect(!!GLOBAL.DEBUG).toEqual(false); 45 | } 46 | }); 47 | }); 48 | describe('findByName', () => { 49 | it('should find root level object', () => { 50 | matches = find.byName('circ'); 51 | testMatches(matches, [ 52 | `GLOBAL.testObj.circ -> (object) ${GLOBAL.testObj.circ}` 53 | ]); 54 | }); 55 | 56 | it('should find root level array', () => { 57 | matches = find.byName('arr1'); 58 | testMatches(matches, [ 59 | `GLOBAL.testObj.arr1 -> (object) ${GLOBAL.testObj.arr1}` 60 | ]); 61 | }); 62 | 63 | it('should find nested property', () => { 64 | matches = find.byName('a'); 65 | testMatches(matches, [ 66 | 'GLOBAL.testObj.circ.a -> (number) 3' 67 | ]); 68 | }); 69 | 70 | it('should detect circular references', () => { 71 | matches = find.byName('d'); 72 | testMatches(matches, [ 73 | 'GLOBAL.testObj.obj.d -> () 4' 74 | ]); 75 | }); 76 | }); 77 | 78 | describe('findByType', () => { 79 | it('should find first class objects types', () => { 80 | matches = find.byType(Array, GLOBAL.testObj); 81 | testMatches(matches, [ 82 | `SRC.arr1 -> (object) ${GLOBAL.testObj.arr1}`, 83 | `SRC.arr2 -> (object) ${GLOBAL.testObj.arr2}` 84 | ]); 85 | logSpy.calls.reset(); 86 | matches = find.byType(Function, GLOBAL.testObj); 87 | testMatches(matches, [ 88 | `SRC.fn -> (function) [object Function]` 89 | ]); 90 | }); 91 | it('should not find primitive types', () => { 92 | matches = find.byType(String, GLOBAL.testObj); 93 | testMatches(matches, []); 94 | }); 95 | }); 96 | 97 | describe('findByValue', () => { 98 | it('should find number', () => { 99 | matches = find.byValue(3, GLOBAL.testObj); 100 | testMatches(matches, [ 101 | 'SRC.circ.a -> (number) 3' 102 | ]); 103 | }); 104 | it('should find number and detect circular reference', () => { 105 | matches = find.byValue(4, GLOBAL.testObj); 106 | testMatches(matches, [ 107 | 'SRC.obj.d -> () 4' 108 | ]); 109 | }); 110 | it('should find complex value', () => { 111 | matches = find.byValue(GLOBAL.testObj.arr2, GLOBAL.testObj); 112 | testMatches(matches, [ 113 | `SRC.arr2 -> (object) ${GLOBAL.testObj.arr2}` 114 | ]); 115 | }); 116 | }); 117 | 118 | describe('findByValueCoreced', () => { 119 | it('should find number equivalent of a string', () => { 120 | matches = find.byValueCoerced('3', GLOBAL.testObj); 121 | testMatches(matches, [ 122 | 'SRC.circ.a -> (number) 3' 123 | ]); 124 | }); 125 | it('should not find falsey values when non exist', () => { 126 | matches = find.byValueCoerced(false, GLOBAL.testObj); 127 | testMatches(matches, []); 128 | }); 129 | }); 130 | 131 | describe('findByCustomFunction', () => { 132 | it('should return custom function matches', () => { 133 | matches = find.custom((what, obj, prop) => (obj[prop] === 1) && (prop == 'num')); 134 | testMatches(matches, [ 135 | 'GLOBAL.testObj.num -> (number) 1' 136 | ]); 137 | }); 138 | it('should report no matches when no custom filter matches', () => { 139 | matches = find.custom((what, obj, prop) => (obj[prop] === 1) && (prop == 'pie')); 140 | testMatches(matches, []); 141 | }); 142 | it('should custom search within given object', () => { 143 | matches = find.custom( 144 | (what, obj, prop) => { 145 | return ( 146 | Array.isArray(obj[prop]) && 147 | typeof obj[prop][0] == 'string' 148 | ); 149 | }, 150 | GLOBAL.testObj 151 | ); 152 | testMatches(matches, [ 153 | 'SRC.arr2 -> (object) a,b,c' 154 | ]); 155 | }); 156 | it('should support destructuring predicates', () => { 157 | const testObj = {a: {a: 3, b: {c: 4, a: {a: {b: 4}}}}}; 158 | matches = find.custom( 159 | (what, obj, prop) => { 160 | let {a: {b: x}} = obj[prop]; 161 | return x === 4; 162 | }, 163 | testObj 164 | ); 165 | testMatches(matches, [ 166 | 'SRC.a.b.a -> (object) [object Object]' 167 | ]); 168 | }); 169 | // TODO: test what param 170 | }); 171 | }); 172 | }); 173 | 174 | /* 175 | node repl crib 176 | 177 | var waldo = require('waldojs'); 178 | var x = {a: {a1: 2, b1: {a2: 8, b2: {a3: 4, b3: 19}}}}; 179 | waldo.custom(function(w, o, p) { 180 | let {a: {b: x}} = obj[prop]; 181 | return x === w; 182 | }, 4, obj); 183 | */ 184 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | entry: './src/waldo.js', 3 | output: { 4 | path: 'lib', 5 | filename: 'waldobundle.js' 6 | }, 7 | module: { 8 | loaders: [ 9 | { 10 | // es6 JavaScript 11 | test: /\.js$/, 12 | loader: 'babel-loader', 13 | exclude: /node_modules/, 14 | query: { 15 | optional: ['runtime'] 16 | } 17 | } 18 | ], 19 | watch: true 20 | } 21 | }; 22 | --------------------------------------------------------------------------------