Merge pull request #973 from atom/ks-underscore-plus

Extract underscore extensions
This commit is contained in:
Kevin Sawicki 2013-10-15 14:48:18 -07:00
commit 697c96921f
48 changed files with 55 additions and 342 deletions

View File

@ -2,7 +2,7 @@ fs = require 'fs'
path = require 'path'
fm = require 'json-front-matter'
_ = require 'underscore'
_ = require 'underscore-plus'
packageJson = require './package.json'

View File

@ -1,8 +1,12 @@
{View, $$, $$$} = require '../src/space-pen-extensions'
{Document, Point, Range, Site} = require 'telepath'
_ = require 'underscore-plus'
#TODO Remove once all packages have been updated
_.nextTick = setImmediate
module.exports =
_: require '../src/underscore-extensions'
_: _
$: require '../src/jquery-extensions'
$$: $$
$$$: $$$

View File

@ -35,10 +35,9 @@
"season": "0.13.0",
"semver": "1.1.4",
"space-pen": "1.3.0",
"tantamount": "0.5.0",
"telepath": "0.8.1",
"temp": "0.5.0",
"underscore": "1.4.4",
"underscore-plus": "0.2.0",
"atom-light-ui": "0.4.0",
"atom-light-syntax": "0.4.0",

View File

@ -1,6 +1,6 @@
$ = require 'jquery'
{View, $$} = require 'space-pen'
_ = require 'underscore'
_ = require 'underscore-plus'
{convertStackTrace} = require 'coffeestack'
sourceMaps = {}

View File

@ -2,7 +2,7 @@ TextMateGrammar = require '../src/text-mate-grammar'
TextMatePackage = require '../src/text-mate-package'
{_, fs} = require 'atom'
describe "TextMateGrammar", ->
fdescribe "TextMateGrammar", ->
grammar = null
beforeEach ->
@ -214,7 +214,7 @@ describe "TextMateGrammar", ->
atom.activatePackage('html-tmbundle', sync: true)
atom.activatePackage('ruby-on-rails-tmbundle', sync: true)
grammar = syntax.selectGrammar('foo.html.erb')
grammar = syntax.grammarForScopeName('text.html.ruby')
{tokens} = grammar.tokenizeLine("<div class='name'><%= User.find(2).full_name %></div>")
expect(tokens[0]).toEqual value: '<', scopes: ["text.html.ruby","meta.tag.block.any.html","punctuation.definition.tag.begin.html"]
@ -263,7 +263,7 @@ describe "TextMateGrammar", ->
atom.deactivatePackage('html-tmbundle')
atom.activatePackage('ruby-on-rails-tmbundle', sync: true)
grammar = syntax.selectGrammar('foo.html.erb')
grammar = syntax.grammarForScopeName('text.html.ruby')
{tokens} = grammar.tokenizeLine("<div class='name'><%= User.find(2).full_name %></div>")
expect(tokens[0]).toEqual value: "<div class='name'>", scopes: ["text.html.ruby"]
expect(tokens[1]).toEqual value: '<%=', scopes: ["text.html.ruby","source.ruby.rails.embedded.html","punctuation.section.embedded.ruby"]

View File

@ -1,117 +0,0 @@
{_} = require 'atom'
describe "underscore extensions", ->
describe "_.adviseBefore", ->
[object, calls] = []
beforeEach ->
calls = []
object = {
method: (args...) ->
calls.push(["original", this, args])
}
it "calls the given function before the advised method", ->
_.adviseBefore object, 'method', (args...) -> calls.push(["advice", this, args])
object.method(1, 2, 3)
expect(calls).toEqual [['advice', object, [1, 2, 3]], ['original', object, [1, 2, 3]]]
it "cancels the original method's invocation if the advice returns true", ->
_.adviseBefore object, 'method', -> false
object.method(1, 2, 3)
expect(calls).toEqual []
describe "_.endsWith", ->
it "returns whether the given string ends with the given suffix", ->
expect(_.endsWith("test.txt", ".txt")).toBeTruthy()
expect(_.endsWith("test.txt", "txt")).toBeTruthy()
expect(_.endsWith("test.txt", "test.txt")).toBeTruthy()
expect(_.endsWith("test.txt", "")).toBeTruthy()
expect(_.endsWith("test.txt", ".txt2")).toBeFalsy()
expect(_.endsWith("test.txt", ".tx")).toBeFalsy()
expect(_.endsWith("test.txt", "test")).toBeFalsy()
describe "_.camelize(string)", ->
it "converts `string` to camel case", ->
expect(_.camelize("corey_dale_johnson")).toBe "coreyDaleJohnson"
expect(_.camelize("corey-dale-johnson")).toBe "coreyDaleJohnson"
expect(_.camelize("corey_dale-johnson")).toBe "coreyDaleJohnson"
expect(_.camelize("coreyDaleJohnson")).toBe "coreyDaleJohnson"
expect(_.camelize("CoreyDaleJohnson")).toBe "CoreyDaleJohnson"
describe "_.dasherize(string)", ->
it "converts `string` to use dashes", ->
expect(_.dasherize("corey_dale_johnson")).toBe "corey-dale-johnson"
expect(_.dasherize("coreyDaleJohnson")).toBe "corey-dale-johnson"
expect(_.dasherize("CoreyDaleJohnson")).toBe "corey-dale-johnson"
expect(_.dasherize("corey-dale-johnson")).toBe "corey-dale-johnson"
describe "_.underscore(string)", ->
it "converts `string` to use underscores", ->
expect(_.underscore("corey-dale-johnson")).toBe "corey_dale_johnson"
expect(_.underscore("coreyDaleJohnson")).toBe "corey_dale_johnson"
expect(_.underscore("CoreyDaleJohnson")).toBe "corey_dale_johnson"
expect(_.underscore("corey_dale_johnson")).toBe "corey_dale_johnson"
describe "spliceWithArray(originalArray, start, length, insertedArray, chunkSize)", ->
describe "when the inserted array is smaller than the chunk size", ->
it "splices the array in place", ->
array = ['a', 'b', 'c']
_.spliceWithArray(array, 1, 1, ['v', 'w', 'x', 'y', 'z'], 100)
expect(array).toEqual ['a', 'v', 'w', 'x', 'y', 'z', 'c']
describe "when the inserted array is larger than the chunk size", ->
it "splices the array in place one chunk at a time (to avoid stack overflows)", ->
array = ['a', 'b', 'c']
_.spliceWithArray(array, 1, 1, ['v', 'w', 'x', 'y', 'z'], 2)
expect(array).toEqual ['a', 'v', 'w', 'x', 'y', 'z', 'c']
describe "_.humanizeEventName(eventName)", ->
describe "when no namespace exists", ->
it "undasherizes and capitalizes the event name", ->
expect(_.humanizeEventName('nonamespace')).toBe 'Nonamespace'
expect(_.humanizeEventName('no-name-space')).toBe 'No Name Space'
describe "when a namespaces exists", ->
it "space separates the undasherized/capitalized versions of the namespace and event name", ->
expect(_.humanizeEventName('space:final-frontier')).toBe 'Space: Final Frontier'
expect(_.humanizeEventName('star-trek:the-next-generation')).toBe 'Star Trek: The Next Generation'
describe "_.deepExtend(objects...)", ->
it "copies all key/values from each object into a new object", ->
first =
things:
string: "oh"
boolean: false
anotherArray: ['a', 'b', 'c']
object:
first: 1
second: 2
second =
things:
string: "cool"
array: [1,2,3]
anotherArray: ['aa', 'bb', 'cc']
object:
first: 1
result = _.deepExtend(first, second)
expect(result).toEqual
things:
string: "oh"
boolean: false
array: [1,2,3]
anotherArray: ['a', 'b', 'c']
object:
first: 1
second: 2
describe "_.isSubset(potentialSubset, potentialSuperset)", ->
it "returns whether the first argument is a subset of the second", ->
expect(_.isSubset([1, 2], [1, 2])).toBeTruthy()
expect(_.isSubset([1, 2], [1, 2, 3])).toBeTruthy()
expect(_.isSubset([], [1])).toBeTruthy()
expect(_.isSubset([], [])).toBeTruthy()
expect(_.isSubset([1, 2], [2, 3])).toBeFalsy()

View File

@ -2,7 +2,7 @@ TextMateGrammar = require './text-mate-grammar'
Package = require './package'
fsUtils = require './fs-utils'
path = require 'path'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
$ = require './jquery-extensions'
CSON = require 'season'
{Emitter} = require 'emissary'

View File

@ -6,7 +6,7 @@ Emitter::subscriptionCount = (args...) -> @getSubscriptionCount(args...)
fsUtils = require './fs-utils'
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
Package = require './package'
ipc = require 'ipc'
remote = require 'remote'

View File

@ -1,5 +1,5 @@
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
Specificity = require '../vendor/specificity'

View File

@ -1,6 +1,6 @@
ChildProcess = require 'child_process'
path = require 'path'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
# Public: A wrapper which provides buffering for ChildProcess.
module.exports =

View File

@ -1,6 +1,6 @@
path = require 'path'
fs = require 'fs'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
async = require 'async'
mkdirp = require 'mkdirp'
fsUtils = require './fs-utils'

View File

@ -1,5 +1,5 @@
fsUtils = require './fs-utils'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
{Emitter} = require 'emissary'
CSON = require 'season'
fs = require 'fs'

View File

@ -1,5 +1,5 @@
$ = require 'jquery'
_ = require 'underscore'
_ = require 'underscore-plus'
remote = require 'remote'
# Public: Provides a registry for commands that you'd like to appear in the

View File

@ -1,6 +1,6 @@
{View} = require './space-pen-extensions'
{Point, Range} = require 'telepath'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
### Internal ###
module.exports =

View File

@ -1,6 +1,6 @@
{Point, Range} = require 'telepath'
{Emitter} = require 'emissary'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
# Public: The `Cursor` class represents the little blinking line identifying
# where text can be inserted.

View File

@ -1,5 +1,5 @@
{Range} = require 'telepath'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
{Emitter, Subscriber} = require 'emissary'
# Private:

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
{Emitter, Subscriber} = require 'emissary'
guid = require 'guid'
telepath = require 'telepath'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
path = require 'path'
telepath = require 'telepath'

View File

@ -7,7 +7,7 @@ CursorView = require './cursor-view'
SelectionView = require './selection-view'
fsUtils = require './fs-utils'
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
MeasureRange = document.createRange()
TextNodeFilter = { acceptNode: -> NodeFilter.FILTER_ACCEPT }
@ -1185,7 +1185,7 @@ class Editor extends View
return if @pendingDisplayUpdate
return unless @isVisible()
@pendingDisplayUpdate = true
_.nextTick =>
setImmediate =>
@updateDisplay()
@pendingDisplayUpdate = false

View File

@ -3,7 +3,7 @@ Q = require 'q'
path = require 'path'
fsUtils = require './fs-utils'
pathWatcher = require 'pathwatcher'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
# Public: Represents an individual file in the editor.
#

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fs = require 'fs'
mkdirp = require 'mkdirp'
Module = require 'module'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
Task = require './task'
{Emitter, Subscriber} = require 'emissary'

View File

@ -1,7 +1,7 @@
{View, $$, $$$} = require './space-pen-extensions'
{Range} = require 'telepath'
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
# Private: Represents the portion of the {Editor} containing row numbers.
#

View File

@ -1,5 +1,5 @@
$ = require '../vendor/jquery'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
$.fn.scrollBottom = (newValue) ->
if newValue?

View File

@ -1,5 +1,5 @@
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
path = require 'path'
CSON = require 'season'

View File

@ -1,5 +1,5 @@
{Range} = require 'telepath'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
{OnigRegExp} = require 'oniguruma'
{Emitter, Subscriber} = require 'emissary'

View File

@ -1,6 +1,6 @@
path = require 'path'
_ = require 'underscore'
_ = require 'underscore-plus'
ipc = require 'ipc'
CSON = require 'season'

View File

@ -1,6 +1,6 @@
{Emitter} = require 'emissary'
fsUtils = require './fs-utils'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
Package = require './package'
path = require 'path'

View File

@ -1,5 +1,5 @@
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
PaneAxis = require './pane-axis'
# Internal:

View File

@ -1,5 +1,5 @@
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
PaneAxis = require './pane-axis'
### Internal ###

View File

@ -1,7 +1,7 @@
{dirname} = require 'path'
{View} = require './space-pen-extensions'
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
telepath = require 'telepath'
PaneRow = require './pane-row'
PaneColumn = require './pane-column'

View File

@ -3,7 +3,7 @@ path = require 'path'
url = require 'url'
Q = require 'q'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
telepath = require 'telepath'
{Range} = telepath
TextBuffer = require './text-buffer'

View File

@ -5,7 +5,7 @@ Q = require 'q'
$ = require './jquery-extensions'
{$$, View} = require './space-pen-extensions'
fsUtils = require './fs-utils'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
telepath = require 'telepath'
Editor = require './editor'
Pane = require './pane'
@ -130,7 +130,7 @@ class RootView extends View
@panes.reopenItem()
if @state.get('fullScreen')
_.nextTick => atom.setFullScreen(true)
setImmediate => atom.setFullScreen(true)
# Private:
serialize: ->

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
spacePen = require 'space-pen'
jQuery = require './jquery-extensions'
ConfigObserver = require './config-observer'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
jQuery = require './jquery-extensions'
Specificity = require '../vendor/specificity'
{$$} = require './space-pen-extensions'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
child_process = require 'child_process'
{Emitter} = require 'emissary'

View File

@ -4,7 +4,7 @@ Q = require 'q'
{P} = require 'scandal'
telepath = require 'telepath'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
File = require './file'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
fsUtils = require './fs-utils'
plist = require 'plist'
Token = require './token'

View File

@ -1,7 +1,7 @@
Package = require './package'
fsUtils = require './fs-utils'
path = require 'path'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
TextMateGrammar = require './text-mate-grammar'
async = require 'async'

View File

@ -3,7 +3,7 @@ path = require 'path'
Package = require './package'
AtomPackage = require './atom-package'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
$ = require './jquery-extensions'
fsUtils = require './fs-utils'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
textUtils = require './text-utils'
WhitespaceRegexesByTabLength = {}

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
TokenizedLine = require './tokenized-line'
{Emitter, Subscriber} = require 'emissary'
Token = require './token'

View File

@ -1,4 +1,4 @@
_ = require './underscore-extensions'
_ = require 'underscore-plus'
### Internal ###

View File

@ -1,173 +0,0 @@
_ = require 'underscore'
_.mixin
remove: (array, element) ->
index = array.indexOf(element)
array.splice(index, 1) if index >= 0
array
spliceWithArray: (originalArray, start, length, insertedArray, chunkSize=100000) ->
if insertedArray.length < chunkSize
originalArray.splice(start, length, insertedArray...)
else
originalArray.splice(start, length)
for chunkStart in [0..insertedArray.length] by chunkSize
originalArray.splice(start + chunkStart, 0, insertedArray.slice(chunkStart, chunkStart + chunkSize)...)
sum: (array) ->
sum = 0
sum += elt for elt in array
sum
adviseBefore: (object, methodName, advice) ->
original = object[methodName]
object[methodName] = (args...) ->
unless advice.apply(this, args) == false
original.apply(this, args)
escapeRegExp: (string) ->
string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
escapeAttribute: (string) ->
string.replace(/"/g, '&quot;').replace(/\n/g, '')
humanizeEventName: (eventName, eventDoc) ->
[namespace, event] = eventName.split(':')
return _.undasherize(namespace) unless event?
namespaceDoc = _.undasherize(namespace)
eventDoc ?= _.undasherize(event)
"#{namespaceDoc}: #{eventDoc}"
capitalize: (word) ->
if word.toLowerCase() is 'github'
'GitHub'
else
word[0].toUpperCase() + word[1..]
pluralize: (count=0, singular, plural=singular+'s') ->
if count is 1
"#{count} #{singular}"
else
"#{count} #{plural}"
camelize: (string) ->
string.replace /[_-]+(\w)/g, (m) -> m[1].toUpperCase()
dasherize: (string) ->
string = string[0].toLowerCase() + string[1..]
string.replace /([A-Z])|(_)/g, (m, letter, underscore) ->
if letter
"-" + letter.toLowerCase()
else
"-"
uncamelcase: (string) ->
result = string.replace /([A-Z])|(_)/g, (m, letter, underscore) -> " " + letter
_.capitalize(result)
undasherize: (string) ->
string.split('-').map(_.capitalize).join(' ')
underscore: (string) ->
string = string[0].toLowerCase() + string[1..]
string.replace /([A-Z])|(-)/g, (m, letter, dash) ->
if letter
"_" + letter.toLowerCase()
else
"_"
losslessInvert: (hash) ->
inverted = {}
for key, value of hash
inverted[value] ?= []
inverted[value].push(key)
inverted
multiplyString: (string, n) ->
new Array(1 + n).join(string)
nextTick: (fn) ->
unless @messageChannel
@pendingNextTickFns = []
@messageChannel = new MessageChannel
@messageChannel.port1.onmessage = =>
fn() while fn = @pendingNextTickFns.shift()
@pendingNextTickFns.push(fn)
@messageChannel.port2.postMessage(0)
endsWith: (string, suffix) ->
string.indexOf(suffix, string.length - suffix.length) isnt -1
# Transform the given object into another object.
#
# `object` - The object to transform.
# `iterator` -
# A function that takes `(key, value)` arguments and returns a
# `[key, value]` tuple.
#
# Returns a new object based with the key/values returned by the iterator.
mapObject: (object, iterator) ->
newObject = {}
for key, value of object
[key, value] = iterator(key, value)
newObject[key] = value
newObject
# Deep clones the given JSON object.
#
# `object` - The JSON object to clone.
#
# Returns a deep clone of the JSON object.
deepClone: (object) ->
if _.isArray(object)
object.map (value) -> _.deepClone(value)
else if _.isObject(object)
@mapObject object, (key, value) => [key, @deepClone(value)]
else
object
deepExtend: (objects...) ->
result = {}
for object in objects
for key, value of object
if _.isObject(value) and not _.isArray(value)
result[key] = @deepExtend(result[key], value)
else
result[key] ?= value
result
valueForKeyPath: (object, keyPath) ->
keys = keyPath.split('.')
for key in keys
object = object[key]
return unless object?
object
setValueForKeyPath: (object, keyPath, value) ->
keys = keyPath.split('.')
while keys.length > 1
key = keys.shift()
object[key] ?= {}
object = object[key]
if value?
object[keys.shift()] = value
else
delete object[keys.shift()]
compactObject: (object) ->
newObject = {}
for key, value of object
newObject[key] = value if value?
newObject
isSubset: (potentialSubset, potentialSuperset) ->
_.every potentialSubset, (element) -> _.include(potentialSuperset, element)
_.isEqual = require 'tantamount'
module.exports = _

View File

@ -1,5 +1,5 @@
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
ipc = require 'ipc'
shell = require 'shell'
{Subscriber} = require 'emissary'

View File

@ -1,6 +1,6 @@
path = require 'path'
$ = require './jquery-extensions'
_ = require './underscore-extensions'
_ = require 'underscore-plus'
ipc = require 'ipc'
WindowEventHandler = require './window-event-handler'
@ -13,7 +13,7 @@ windowEventHandler = null
# This is done in a next tick to prevent a white flicker from occurring
# if called synchronously.
displayWindow = ->
_.nextTick ->
setImmediate ->
atom.show()
atom.focus()

View File

@ -1,6 +1,6 @@
path = require 'path'
_ = require 'underscore'
_ = require 'underscore-plus'
plist = require 'plist'
{ScopeSelector} = require 'first-mate'

View File

@ -1,7 +1,7 @@
fs = require 'fs'
path = require 'path'
_ = require 'underscore'
_ = require 'underscore-plus'
async = require 'async'
module.exports = (grunt) ->