Skip to content

Instantly share code, notes, and snippets.

@stevenewey
Created August 30, 2012 12:28
Show Gist options
  • Save stevenewey/3527537 to your computer and use it in GitHub Desktop.
Save stevenewey/3527537 to your computer and use it in GitHub Desktop.
Summarise array (optionally on item property) into human readable string
Array::summarise = (args) ->
count = args?.maximumItems or 3
if typeof args?.property == 'string'
temp = []
[temp.push item[args.property] for item in this]
else
temp = this[...]
if temp.length > 1 and temp.length <= count
return temp[...-1].join(', ') + ' and ' + temp[-1...]
else if temp.length == 1
return temp[0]
else if temp.length > count
return temp[...(count-1)].join(', ') + ' and ' + temp[(count-1)...].length + ' others'
else
return
a = Array('stephen', 'jay', 'peter', 'toby', 'olly')
console.log(a.summarise())
console.log(a.summarise({maximumItems: 5}))
console.log(a.summarise({maximumItems: 4}))
console.log('')
b = Array('stephen')
console.log(b.summarise())
console.log('')
c = Array('stephen', 'jay')
console.log(c.summarise())
console.log('')
d = Array('stephen', 'jay', 'peter')
console.log(d.summarise())
console.log('')
e = [
{name: 'Stephen'}
{name: 'Jay'}
{name: 'Peter'}
{name: 'Toby'}
{name: 'Olly'}
]
console.log e.summarise
maximumItems: 3
property: 'name'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment