Created
April 23, 2018 12:12
-
-
Save hafidbuilds/d0035c6fb40a2d8afdd3b8a1544397eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
given an array of numbers, | |
return a new array in which each number is doubled | |
*/ | |
function map(array, instruction) { | |
let newArr = [] | |
for (let item of array) { | |
newArr.push(instruction(item)) | |
} | |
return newArr | |
} | |
const double = item => item * 2 | |
const result = map([1,2,3,4], double) | |
/* | |
given an array of objects, | |
pluck a specific property from each | |
*/ | |
function pluck(array, propName) { | |
let newArr = [] | |
for (let item of array) { | |
if (item.hasOwnProperty(propName)) { | |
newArr.push(item[propName]) | |
} | |
} | |
return newArr | |
} | |
const profiles = [ | |
{ | |
address: 'Jakarta', | |
}, | |
{ | |
name: 'Hafidz', | |
age: 22, | |
}, | |
{ | |
name: 'Ilham', | |
age: 50, | |
}, | |
{ | |
name: 'Aji', | |
age: 10, | |
} | |
] | |
const result1 = pluck(profiles, 'names') | |
const result2 = pluck(profiles, 'name') | |
const result3 = pluck(profiles, 'address') | |
const result4 = pluck(profiles, 'age') | |
/* | |
compare two values, shallow comparing content in arrays | |
*/ | |
function shallowCompare(array1, array2) { | |
let result = true | |
if (array1.length != array2.length) { | |
result = false | |
} else { | |
for (let i = 0; i < array1.length; i++) { | |
if (array1[i] !== array2[i]) { | |
result = false | |
} | |
} | |
} | |
return result | |
} | |
const result1 = shallowCompare([1,2,3], [1,2,3]) | |
const result2 = shallowCompare([1,2,3], [6,2]) | |
const result3 = shallowCompare([1,2,3], [1,2,3,4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment