const _ = require('../lib/underScore.js')
const Utils = function() {}
Utils.existy = function(x) {
return x != null
}
Utils.truthy = function(x) {
return (x != false) && this.existy(x)
}
let zombie = {name: 'Bub', film: "Day of the dead"}
console.log( _.keys(zombie))
console.log( _.values(zombie))
let book = [
{title: 'js', author: 'a'},
{title: 'java', author: 'b'},
{title: 'rust', author: 'c'},
]
console.log(_.pluck(book, 'title'))
console.log(_.pairs(book))
console.log(_.pairs(zombie))
let res = _.object(_.pairs(zombie).map((pair) => [pair[0].toUpperCase(), pair[1]]))
console.log('res', res)
console.log(_.invert(zombie))
res = _.pluck(book.concat({title: 'python'}).map((obj) => _.defaults(obj, {author: 'unknown'})), 'author')
console.log(res)
let person = {name: 'ruby', token: 'jdh', password: 'test'}
console.log(_.omit(person, 'token', 'password'))
console.log(_.pick(person, 'token', 'password'))
let library = [
{
title: '数据结构',
ed:1,
author: '蔚敏老师'
},
{
title: '算法',
ed:2,
author: '左大'
},
{
title: '算法',
ed:3,
author: '阿北'
},
{
title: 'es6',
ed:3,
author: '阮一峰'
}
]
console.log(_.findWhere(library, {title: '算法'}))
console.log(_.where(library, {title: '算法'}))
function project(table, keys) {
return table.map(item => _.pick(item, ...keys))
}
let ebook = project(library, ['title', 'ed'])
console.log(ebook)
let ebook2 = project(ebook, ['title'])
console.log(ebook2)
console.log(_.pluck(ebook2, 'title'))
function rename (obj, newNames) {
let pre = _.omit(obj, ..._.keys(newNames))
return _.reduce(newNames, (pre, cur, key) => {
if(_.has(obj, key)) {
pre[cur] = obj[key]
return pre
} else {
return pre
}
}, pre)
}
console.log(rename({a:1, b:2}, {'a': 'AA'}))
function as (table, newNames) {
return table.map(item => rename(item,newNames))
}
console.log(as(library, {ed: "eid"}))
console.log(project(as(library, {ed: 'myEid'}), ['myEid']))
function restrict(table, pred) {
return _.reduce(table, function(newTable, obj) {
if(Utils.truthy(pred(obj))) {
return newTable
} else {
return _.without(newTable, obj)
}
}, table)
}
book = restrict(library, function(book){
return book.ed > 1
})
console.log(book)