Skip to content

Commit

Permalink
perf(util): optimize each() and map()
Browse files Browse the repository at this point in the history
  • Loading branch information
Bo Lingen committed Jul 26, 2017
1 parent da842df commit 040084d
Showing 1 changed file with 33 additions and 21 deletions.
54 changes: 33 additions & 21 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,41 @@ import { dirname } from 'path'
import { mkdirSync, statSync } from 'fs'
import type from 'component-type'

export const map = (object, fn) => each(object, fn, true)

export function each (object, fn, map) {
if (isObject(object)) {
if (map) {
const res = {}

Object.keys(object).forEach(key => {
res[key] = fn.call(object, object[key], key, object)
})

return res
} else {
Object.keys(object).forEach(key => {
fn.call(object, object[key], key, object)
})
export function each (collection, fn) {
const kind = type(collection)

if (kind === 'object') {
const keys = Object.keys(collection)

for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const value = collection[key]
if (fn(value, key, collection) === false) break
}
} else if (isArray(object)) {
const method = map ? 'map' : 'forEach'
return object[method](fn)
} else {
return object

return
}

if (kind === 'array') {
for (let i = 0; i < collection.length; i++) {
const value = collection[i]
if (fn(value, i, collection) === false) break
}
}
}

export function map (collection, fn) {
const kind = type(collection)
if (kind !== 'object' && kind !== 'array') {
return collection
}

const result = kind === 'array' ? [] : {}
each(collection, (value, key, collection) => {
result[key] = fn(value, key, collection)
})

return result
}

export function isOneOf (array, value) {
Expand Down

0 comments on commit 040084d

Please sign in to comment.