Object Key Order and Reflect.ownKeys
copy const obj = { 11 : 'eleven' , 23 : 'twenty-three' , 1 : 'one' , 2 : 'two' , '-1' : 'negative 1' } ; console.log ( Reflect.ownKeys ( obj) )
Try it out
I noticed that for in..
over an object was giving me weirdly consistent results across all browsers the other day and stumbled upon this.
Great news, but it’s Reflect.ownKeys
for me… now that IE11 is dying/dead.
Step Between Two Numbers
copy const stepBetweenA = ( min, max, steps) => Array ( steps) .fill ( 0 ) .reduce ( ( prev, curr, i) => { prev.push ( min + ( ( max - min) / ( steps - 1 ) ) * i) return prev } , [ ] ) const stepBetweenB = ( min, max, steps) => { steps -= 1 const diff = ( max - min) / steps const result = [ min] for ( let i = 0 ; i < steps; i++ ) { result.push ( min += diff) } return result } console.log ( 'a' , stepBetweenA( 10 , 110 , 4 ) ) console.log ( 'b' , stepBetweenB( 10 , 110 , 4 ) ) const ITER = 10000 console.time ( 'a' ) for ( let i = 0 ; i < ITER; i++ ) { stepBetweenA( 10 , 110 , 4 ) } console.timeEnd ( 'a' ) console.time ( 'b' ) for ( let i = 0 ; i < ITER; i++ ) { stepBetweenB( 10 , 110 , 4 ) } console.timeEnd ( 'b' )
Try it out…
Two messy implementations for stepping between two numbers… I am not sure it’s possible to make console.time
work well with the snippet zone quick editor – so if you want to see the times… open your console.
Alphabet Array JavaScript
copy const alphabet = 'abcdefghijklmnopqrstuvwxyz' .split ( '' ) console.log ( alphabet) ; // outputs: ['a', 'b', 'c', ... 'z']
Try it out…
Create an array of the alphabet.
Splitting a string with an empty string results in each character being placed into a slot in the new array.
Merge Collection (array of objects)
copy const collection = [ { name: 'Joe' } , { age: 31 } , { job: 'programmer' } ] ; const merged = Object .assign ( { } , ...collection ) ; console.log ( merged) ;
Try it out…
Combine (“assign”) entire array of objects.
Saw this here… figured it was worth a quick post.
Guess the semi-golf
copy a= 3217 + '' ; a= [ a] ; console.log ( a[ 0 ] [ 2 ] )
Try and guess what would be logged here…