Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Hayden Perry committed Feb 1, 2020
0 parents commit 72ad84d
Show file tree
Hide file tree
Showing 6 changed files with 291 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = {
env: {
commonjs: true,
node: true,
es6: true
},
extends: 'eslint:recommended',
parser: 'babel-eslint',
parserOptions: {
esmaVersion: 9
},
sourceType: 'module',
rules: {
'new-cap': 'off',
'no-unused-vars': 'off',
'no-console': 'off',
'no-debugger': 'off',
'linebreak-style': [ 'error', 'unix' ],
indent: [ 'error', 2 ],
quotes: [ 'error', 'single' ],
semi: [ 'error', 'never' ]
}
}
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules/
.env
.env.*
*.env
.vscode/
.DS_STORE
.DS_STORE?
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2020 Hayden Perry

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
160 changes: 160 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Yankee Doodle

A Lodash.pick inspired JavaScript package to pick object values from plain JavaScript objects. Other packages lacked what I needed from an object property picker so I created this. Zero dependencies and works in all major web browsers plus Node.

## Getting Started

Super simple to use, although there are some limitations with what you can parse. If your objects are complicated, make them simpler! Data should be simple and easy to read.

### Installing

```
npm i yankee-doodle
```

### Demo

Given the the data below, you can yank values from an object using a schema or collection of schemas to build a new object with those values.

``` javascript
import yank from 'yankee-doodle'

const data = {
firstName: 'John',
lastName: 'Doe',
dateOfBirth: '1985-01-01',
addressDetails: {
address1: '10 Downing Street',
address2: null,
address3: null,
city: 'London',
postcode: 'SW1A 2AB'
},
nested: {
data: {
items: {
one: 'one',
two: 'two',
three: 'three'
}
}
}
}
```

Simply spread the property names into the `yank` method and it will return only those values from the given object.

``` javascript
yank(data, 'firstName', 'lastName')
// {
// "firstName": "John",
// "lastName": "Doe"
// }
```

Have a nested object? Similar to JSON markup, use `{` and `}` to yank children properties. This can be as nested as you like.

``` javascript
yank(data, 'addressDetails: { address1, city }', 'firstName')
// {
// "addressDetails": {
// "address1": "10 Downing Street",
// "city": "London"
// },
// "firstName": "John"
// }
```

Deeply nesting is possible like so.

``` javascript
yank(data, 'nested: { data: { items: { one, two } } }')
// {
// "nested": {
// "data": {
// "items": {
// "one": "one",
// "two": "two"
// }
// }
// }
// }
```

You can even provide your schema with whitespace if you felt so inclined to format at this way.

``` javascript
yank(data, `
nested: {
data: {
items: {
one,
two
}
}
}
`)
// {
// "nested": {
// "data": {
// "items": {
// "one": "one",
// "two": "two"
// }
// }
// }
// }
```

You can even rename properties by providing the original property name followed by `->` and then the new property name you would like to change it to. This works for any given property anywhere in the schema, including nested properties.

``` javascript
yank(data, 'firstName->first_name', 'lastName->last_name', 'addressDetails->address_details: { city }')
// {
// "first_name": "John",
// "last_name": "Doe",
// "address_details": {
// "city": "London"
// }
// }
```

Yanking properties that don't exist will result in nothing happening for that particular key. Example below demonstrates that an empty object is returned because neither of the given properties exist on the original data object.

``` javascript
yank(data, 'emailAddress', 'phoneNumber')
// {}
```

Mixing existing properties with properties that don't exist works too. The ones that don't exist simply get ignored.

``` javascript
yank(data, 'addressDetails: { county }', 'addressDetails: { city }', 'dateOfBirth')
// {
// "addressDetails": {
// "city": "London"
// },
// "dateOfBirth"
// }
```

## Todo

- Add Lodash style path keys for selecting deeply nested properties
- Add tests

## Tests

**Soon to be added**

## Authors

* **Hayden Perry** - *Maintainer* - [bakewellcake](https://github.com/bakewellcake)

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.

## Acknowledgments

* Heavily inspired by [Lodash.pick](https://github.com/lodash/lodash/blob/master/pick.js) and [supick](https://github.com/PavloAndriiesh/supick).
67 changes: 67 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const { entries, values, getPrototypeOf } = Object

function yank (object, ...args) {
if (args.length === 0) return object

const schemaList = args.flat()
const yanked = {}

if (!schemaList.every(arg => typeof arg === 'string')) throw 'All arguments must be strings'

for (const schema of schemaList) {
const parsedArgs = schema
.replace(/\s+/g, '')
.replace(/([\w->]+)/g, '"$1"')
.replace(/((?<!}),|(?<=")\s?}|(?<!})$)/g, ':0$1')
const parsedSchema = JSON.parse(`{${parsedArgs}}`)

walk(object, yanked, parsedSchema)
}

return yanked
}

function walk (object, yanked, schema) {
for (const [key, value] of entries(schema)) {
const [originalKey, renamedKey] = key.split('->')
const newKey = renamedKey || originalKey

if (object.hasOwnProperty(originalKey)) {
const { length } = values(value || {})

if (length) walk(object[originalKey], yanked[newKey] = {}, schema[key])
else yanked[newKey] = object[originalKey]
}

prune(yanked)
}
}

function prune (yanked) {
for (const [key, value] of entries(yanked)) {
const { length } = values(value)

if (!length) {
let proto = value

while ((proto = getPrototypeOf(proto)) !== null)

if (getPrototypeOf(value) === proto) delete yanked[key]
}
}
}

const data = {
test1: 'test',
test2: 'test',
test3: {
test4: 'test',
test5: 'test'
}
}

const picked = yank(data, ` test1, test3: { test4, test5 } `)

console.log(picked)

module.exports = yank
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "yankee-doodle",
"version": "1.0.0",
"scripts": {},
"description": "Yank values a from given object via a specified schema",
"author": "Hayden Perry [email protected]",
"repository": {
"type": "git",
"url": "https://github.com/bakewellcake/yankee-doodle"
},
"main": "index.js",
"keywords": ["yank", "yanked", "pick", "picked", "pluck", "plucked", "schema"]
}

0 comments on commit 72ad84d

Please sign in to comment.