Skip to content

Instantly share code, notes, and snippets.

@xieranmaya
Last active September 3, 2017 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xieranmaya/bdbd84968f064c2675b7b5ea4e74fe26 to your computer and use it in GitHub Desktop.
Save xieranmaya/bdbd84968f064c2675b7b5ea4e74fe26 to your computer and use it in GitHub Desktop.
var lodash = {}
lodash.chunk = chunk = (array, size = 1) => array.reduce((x, y, i) => (i % size === 0 ? x.push([y]) : x[i / size | 0].push(y), x), [])
lodash.compact = (array) => array.filter(x => x)
lodash.concat = (array, ...args) => args.reduce((x, y) => (Array.isArray(y) ? x.push(...y) : x.push(y), x), array)
lodash.difference = (array, values) => array.reduce((x, y) => (~values.indexOf(y) || x.push(y), x), [])
lodash.drop = (array, n = 1) => array.reduce((x, y, i) => (i >= n && x.push(y), x), [])
lodash.fill = (array, value, start = 0, end = array.length) => ([...array].some((x, i) => start <= i && i < end && (array[i] = value) && i >= end && true), array)
lodash.head = array => array[0]
lodash.flatten = array => array.reduce((a, b) => a.concat(b), [])
lodash.flattenDeep = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? lodash.flattenDeep(b) : b), [])
lodash.flattenDepth = function flattenDepth(array, depth = 1) {
return array.concat().reduce((a, b) => a.concat(Array.isArray(b) && depth > 1 ? flattenDepth(b, --depth) : b), [])
}
lodash.fromPairs = pairs => pairs.reduce((a, b) => (a[b[0]] = b[1], a), {})
lodash.intersection = (...arg) => arg[0].reduce((x, y) => (arg.every(a => a.includes(y)) && x.push(y), x), [])
lodash.join = (array, separator = ",") => array.reduce((a, b, i) => i === 0 ? b + "" : a + separator + b, "")
lodash.pull = (array, ...value) => [...array].reduce((x, y, i, arr) => (value.includes(y) && x.splice(i - arr.length + array.length, 1), x), array)
lodash.pullAll = (array, values) => lodash.pull(array, ...values)
lodash.reverse = array => array.reduce((x, y, i) => (i < Math.floor(array.length / 2) && ([x[i], x[array.length - 1 - i]] = [x[array.length - 1 - i], x[i]]), x), array)
//解法2: array.sort(() => 1) // 实际上这样做是不行的,取决于所用的排序算法
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment