30-seconds-of-code: purity of dropElements

Created on 18 Dec 2017  路  3Comments  路  Source: 30-seconds/30-seconds-of-code

Up until dropElements all functions are pure.

dropElements, however, is destructive because of Array.shift.

It can be made pure using Array.prototype.slice:

const dropElements = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]

Not sure if this is even a concern, but I'm happy to make a PR :)

bug enhancement

Most helpful comment

Unless explicitly stated in the description, functions should not mutate their arguments. Feel free to submit a PR fixing this!

All 3 comments

Unless explicitly stated in the description, functions should not mutate their arguments. Feel free to submit a PR fixing this!

Also, for anyone who comes across this issue and is interested in the subtlety, slice will always return an array, while shift could return undefined:

// Array.prototype.slice :: array -> array
[].slice()
// => []
// Array.prototype.shift :: array -> array || undefined
[].shift()
// => undefined 

Functions that always return the same type eliminate the need to check for failure cases:

const myArr = [];

myArr.slice(1)
    .map(x => x + 1)
    .filter(x => x > 1)
// []

myArr.shift()
    // throws an error here: Cannot read property 'map' of undefined
    .map(x => x + 1)
    .filter(x => x > 1)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fuchao2012 picture fuchao2012  路  4Comments

fejes713 picture fejes713  路  4Comments

Lucien-X picture Lucien-X  路  5Comments

Chalarangelo picture Chalarangelo  路  5Comments

henrycjchen picture henrycjchen  路  4Comments